Home > Blockchain >  C# is there a way to write an instance of a class to a txt file
C# is there a way to write an instance of a class to a txt file

Time:07-03

I am new to c# so im not sure if this is a stupid question or not but.. i have a class with variables inside of it

public class A {
     string name;
     int age;

     public A() {
          Console.WriteLine("Input name");
          name = Console.ReadLine();
          //...
     }
}

and then ill create an instance of this class

static void Main(string[] args) {

      //some code
      A abc = new A();  

}

and i want to save the instance to a txt file. sorta like a save/load system from a game

i tried solutions like using xml, streamWriter, and others but all of them would just cause more errors in my program

im not even sure if this is possible but, Thanks

CodePudding user response:

Yes, it's possible – it's called serialization. Currently .NET supports it among others with System.Text.Json standard library namespace since .NET Core 3.0.

For example, to serialize your object to JSON document, you can use JsonPropertyName property with your fields:

using System.Text.Json.Serialization;

public class A
{
    [JsonPropertyName("name")]
    public string Name { get; set; }

    [JsonPropertyName("age")]
    public int Age { get; set; }

    public A()
    {
        Console.WriteLine("Input name");
        name = Console.ReadLine();
        //...
    }
}

And serialize your object to JSON-formatted string:

using System.Text.Json;

A someObj = new();

// some magic

string jsonContent = JsonSerializer.Serialize(someObj); // output like this: {"name":"some name","age":29}

Now you have to just save it in proper file path specified in your application to save and load it when it's needed.

  •  Tags:  
  • c#
  • Related