0

I've got a class of payments:

class Payments
{
    public string id;    //it must be string because of a method
    public string name;
    public int payment;
}

And a list of objects:

private List<Payments> database = new List<Payments>();

The question is: How can I write it in a file (which is located in the solution's folder) in the easiest way? It shouldn't be the most efficient.

david781
  • 1
  • 1
  • 2

2 Answers2

2

You can use Newtonsoft json to easily serialize this list of objects into json and write that to a file,

using (StreamWriter file = File.CreateText(@"f:\payments.json"))
{
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(file, database);
}
WaughWaugh
  • 1,012
  • 10
  • 15
-1

mark your class with [Serializable] attribute and use generic build in serializer class. You can use it like this

public static void Serialize<T>(T objectToSerialize, string path)
  where T : class
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    using (var writer = new StreamWriter(path))
    {
        serializer.Serialize(writer, objectToSerialize);
    }
}

where T is your Payments class and path is your destination path. In this approach you will serialize it to xml structure, you can easily swap it into binary structure, by using other serializer class. As long as only public properties will by serialized you need to replace your public fields with public properties with public get set accessors.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Asvv
  • 44
  • 1
  • 5