Skip to content

Mike Simmons

My Workbench

  • Home
  • LinkedIn
  • Home
  • Programming
  • Easily save and load C# classes using XML Serialization

Easily save and load C# classes using XML Serialization

Posted on March 16, 2018March 16, 2018 By Mike No Comments on Easily save and load C# classes using XML Serialization
C#, Programming, XML

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");

Tags: C# Serialization XML

Post navigation

❮ Previous Post: Graylog extractors for Sophos UTM logs
Next Post: C# save DataTable to CSV easily ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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.

Pages

  • LinkedIn

Recent Posts

  • PowerShell Anti-Idle Script
  • WSUS MMC Crash Due To XML Invalid Character!
  • Open Maintenance – Docker & CentOS 7
  • Powershell script to create user home directory and DFS namespace target
  • C# save DataTable to CSV easily

Recent Comments

    Archives

    • August 2022
    • March 2018
    • July 2017
    • August 2015

    Categories

    • Active Directory
    • C#
    • CentOS
    • Docker
    • GrayLog
    • MSSQL
    • Networking
    • PowerShell
    • Programming
    • Uncategorized
    • Windows
    • XML

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org

    Copyright © 2023 Mike Simmons.

    Theme: Oceanly by ScriptsTown