Easily save and load C# classes using XML Serialization

These two functions below have saved me a lot of time, you simply create a class with variables inside it and then pass said class to the two functions below:

 
Example Class:

public class ExampleClass
{
string string1 = "testing"
decimal decimal1 = decimal.Parse("64.234234234");
}

Save and load functions:

public T LoadXml(string file)
{
var tSerializer = new XmlSerializer(typeof(T));
using (var streamReader = new StreamReader(file))
{
return (T)tSerializer.Deserialize(streamReader);
}
}


public void SaveXml(string file, T set)
{
var tSerializer = new XmlSerializer(typeof(T));
using (var streamWriter = new StreamWriter(file))
{
tSerializer.Serialize(streamWriter, set);
}
}

To save the class to a XML do the following:

var exampleClass = new ExampleClass();
SaveXml("Filepath", exampleClass);

To load the saved information back into the class:

var exampleClass = LoadXml("Filepath");

Leave a Reply

Your email address will not be published.

I accept that my given data and my IP address is sent to a server in the USA only for the purpose of spam prevention through the Akismet program.More information on Akismet and GDPR.