Serilization. How to serialize multiple lists into one file?

Viewed 111

I can shove one sheet into a file, but how can I save several sheets? How do I refer to them individually?

List<string> Lines = new List<string>()
                    {
                       "1",
                       "2",
                       "3"
                    };
        
                    FileStream fsout = new FileStream("peop.dat",
                        FileMode.Create, FileAccess.Write);
                    XmlSerializer serializerout = new XmlSerializer(typeof(List<string>),
                        new Type[] { typeof(string) });
                    serializerout.Serialize(fsout, Lines,);
                    fsout.Close();
        
                    List<string> Lines1 = new List<string>();
                    FileStream fsin = new FileStream("peop.dat", FileMode.Open,
                        FileAccess.Read);
                    XmlSerializer serializerin = new XmlSerializer(typeof(List<string>),
                        new Type[] { typeof(string) });
                    Lines1 = (List<string>)serializerin.Deserialize(fsin);
                    fsin.Close();
2 Answers

As @Sinatr indicated, the best approach is List or Dictionary of your lists. If you combine that with the .Save() and .Load() extension methods in the "Extensions.cs" NuGet package, the code becomes as simple as this:

        using Extensions;

        List<List<string>> data = new List<List<string>>();
        //Populate your lists with data here.
        data.Save("file.txt");
        data.Load("file.txt");
List<List<string>> reply = new List<List<string>>();
            
            List<string> Lines = new List<string>()
            {
               "1",
               "2",
               "3"
            };
            List<string> Lines2 = new List<string>()
            {
               "4",
               "5",
               "6"
            };
            reply.Add(Lines);
            reply.Add(Lines2);

            FileStream fsout = new FileStream("peop.dat",
                FileMode.Create, FileAccess.Write);
            XmlSerializer serializerout = new XmlSerializer(typeof(List<List<string>>),
                new Type[] { typeof(string) });
            serializerout.Serialize(fsout, reply);
            fsout.Close();

            List<List<string>> Lines1 = new List<List<string>>();
            FileStream fsin = new FileStream("peop.dat", FileMode.Open,
                FileAccess.Read);
            XmlSerializer serializerin = new XmlSerializer(typeof(List<List<string>>),
                new Type[] { typeof(string) });
            Lines1 = (List<List<string>>)serializerin.Deserialize(fsin);
            fsin.Close();
            Random r = new Random();
            return Lines1[1][r.Next(0, Lines.Count)];
Related