MAWood
MAWood

Reputation: 99

Serialization with c# code error

I'm trying to generalize the serialization for one of my projects.

I have three main classes as follows:

test.cs - a simple test object

[Serializable()]
    public class test : Attribute {

        public string name = "";
        public int ID = 0;

        public test(string inputName, int inputID) {
            name = inputName;
            ID = inputID;
        }
        public test() {}
    }

Serialization.cs - my main serialization class

public static void SerializeCollection<T>(string path, List<T> collection, Type type) {
            System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(type);
            System.IO.StreamWriter file = new System.IO.StreamWriter(path);
            writer.Serialize(file, collection);
}

and finally Form1.cs - my form class

    private void btnSerialize_Click(object sender, EventArgs e)
    {
        List<test> test = new List<test>();
        test.Add(new test("testing1", 2));
        Serialization.SerializeCollection("Test.txt", test, typeof(test));
    }

When run and click the button I get this error:

'An unhandled exception of type 'System.InvalidOperationException' occurred in System.Xml.dll

Additional information: There was an error generating the XML document.'

Upvotes: 2

Views: 3462

Answers (1)

Igor Tkachenko
Igor Tkachenko

Reputation: 1120

You use incorrect type for serialization, you have change typeof(test) to typeof(List)

    private static void SerializationTest()
    {
        List<test> test = new List<test>();
        test.Add(new test("testing1", 2));
        SerializeCollection("Test.txt", test, typeof(List<test>));
    }

And to be honest, I would avoid type as a parameter for your method in your case:

    private static void SerializationTest()
    {
        const string fileName = "Test.txt";
        var tests = new List<test> {new test("testing1", 2)};            
        SerializeCollection(fileName, tests);
    }

    public static void SerializeCollection<T>(string fullFileName, IEnumerable<T> items)
    {
        var writer = new XmlSerializer(items.GetType());            
        var file = new StreamWriter(fullFileName);
        writer.Serialize(file, items);
    }

Upvotes: 1

Related Questions