1

If I create a class in C#, how can I serialize/deserialize it to a file? Is this somethat that can be done using built in functionality or is it custom code?

2 Answers 2

3

XmlSerializer; note that the exact xml names can be controlled through various attributes, but all you really need is:

  • a public type
  • with a default constructor
  • and public read/write members (ideally properties)

Example:

using System;
using System.Xml;
using System.Xml.Serialization;
public class Person {
    public string Name { get; set; }
}

static class Program {
    static void Main() {
        Person person = new Person { Name = "Fred"};
        XmlSerializer ser = new XmlSerializer(typeof(Person));
        // write
        using (XmlWriter xw = XmlWriter.Create("file.xml")) {
            ser.Serialize(xw, person);
        }
        // read
        using (XmlReader xr = XmlReader.Create("file.xml")) {
            Person clone = (Person) ser.Deserialize(xr);
            Console.WriteLine(clone.Name);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to use class XmlSerializer. Main methods are Serialize and Deserialize. They accept streams, text readers\writers and other classes.

Code sample:

public class Program
{
    public class MyClass
    {
        public string Name { get; set; }
    }

    static void Main(string[] args)
    {
        var myObj = new MyClass { Name = "My name" };
        var fileName = "data.xml";

        var serializer = new XmlSerializer(typeof(MyClass));

        using (var output = new XmlTextWriter(fileName, Encoding.UTF8))
            serializer.Serialize(output, myObj);

        using (var input = new StreamReader(fileName))
        {
            var deserialized = (MyClass)serializer.Deserialize(input);
            Console.WriteLine(deserialized.Name);
        }

        Console.WriteLine("Press ENTER to finish");
        Console.ReadLine();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.