Beispiel #1
0
        public static void SerializeXmlToFile(string xmlFilePath, List <Person> data)
        {
            // XmlSerializer was made pre-generics and has not been updated
            var serializer = new XmlSerializer(typeof(List <Person>));

            // "using statement" replaces a try-finally-dispose on an disposable object.

            try
            {
                //using (fileStream = new FileStream(xmlFilePath, FileMode.Create))
                //{
                //    serializer.Serialize(fileStream, data);

                //    // at the end of the using block, the object is disposed automatically (regardless
                //    // of any unhandled exceptions)
                //}

                // from c# 8, we have "using declaration" - instead of having to indent a whole block,
                // the implicit dispose will happen at the end of the current block
                using var fileStream = new FileStream(xmlFilePath, FileMode.Create);

                // to make this async, i would load the file contents asynchronously into
                // a memorystream, then give the serializer that memorystream

                // xmlserializer doesnt directly have async support
                serializer.Serialize(fileStream, data);
            }
            catch (IOException ex)
            {
                Console.WriteLine($"Error while opening {xmlFilePath} for writing: {ex.Message}");
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine($"Error while serializing: {ex.Message}");
            }
        }
Beispiel #2
0
        public void ReadXMLFile()
        {
            XMLWrite.Book b = new XMLWrite.Book {
                title = "Serialization Overview"
            };
            XmlSerializer writer = new XmlSerializer(typeof(XMLWrite.Book));
            StreamWriter  wfile  = new StreamWriter(@"e://serialxmldemo.xml");

            writer.Serialize(wfile, b);
            wfile.Close();

            // Now we can read the serialized book ...
            XmlSerializer reader =
                new XmlSerializer(typeof(XMLWrite.Book));
            StreamReader file = new StreamReader(
                @"e://serialxmldemo.xml");

            XMLWrite.Book overview = (XMLWrite.Book)reader.Deserialize(file);
            Console.WriteLine("title=" + overview.title);
            Console.ReadLine();
            file.Close();

            Console.WriteLine(overview.title);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            var groups   = new List <Group>();
            var students = new List <Student>();

            for (int i = 0; i < 10; i++)
            {
                groups.Add(new Group(i, $"Group{i}"));
            }
            for (int i = 0; i < 300; i++)
            {
                var student = new Student(Guid.NewGuid()
                                          .ToString()
                                          .Substring(0, 5), i % 100)
                {
                    Group = groups[i % 9]
                };
                students.Add(student);
            }
            Console.WriteLine("bin");
            var binaryFormatter = new BinaryFormatter();

            using (var file = new FileStream("groups.bin", FileMode.OpenOrCreate))
            {
                binaryFormatter.Serialize(file, groups);
            }

            using (var file = new FileStream("groups.bin", FileMode.OpenOrCreate))
            {
                var newGroups = binaryFormatter.Deserialize(file) as List <Group>;
                if (newGroups is not null)
                {
                    foreach (var group in newGroups)
                    {
                        Console.WriteLine($"{group}");
                    }
                }
            }
            Console.WriteLine("xml");
            var xmlSerializer = new XmlSerializer(typeof(List <Group>));

            using (var file = new FileStream("groups.xml", FileMode.OpenOrCreate))
            {
                xmlSerializer.Serialize(file, groups);
            }

            using (var file = new FileStream("groups.xml", FileMode.OpenOrCreate))
            {
                var newGroups = xmlSerializer.Deserialize(file) as List <Group>;
                if (newGroups is not null)
                {
                    foreach (var group in newGroups)
                    {
                        Console.WriteLine($"{group}");
                    }
                }
            }

            Console.WriteLine("json");
            using (var file = new FileStream("students.json", FileMode.OpenOrCreate))
            {
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    Formatting = Formatting.Indented
                };
                var jsonConverter = JsonConvert.SerializeObject(students, settings);
                file.Write(Encoding.UTF8.GetBytes(jsonConverter), 0, jsonConverter.Length);
            }
            using (var file = new FileStream("students.json", FileMode.OpenOrCreate))
            {
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    Formatting = Formatting.Indented
                };
                byte[] array = new byte[file.Length];
                file.Read(array, 0, array.Length);
                var newStudents = JsonConvert.DeserializeObject <List <Student> >(Encoding.UTF8.GetString(array), settings);

                foreach (var student in newStudents)
                {
                    Console.WriteLine($"{student.Name}({student.Age})");
                }
            }
            Console.ReadKey();
        }