List<Person> parts = new List<Person>(); XmlSerializer xs = new XmlSerializer(typeof(List<Person>)); //Код десериализации ломает программу if (File.Exists("person.xml")){ using (FileStream fs = new FileStream("person.xml", FileMode.OpenOrCreate)) { List<Person> newParts = (List<Person>)xs.Deserialize(fs); Console.WriteLine("Объект десериализован");} }while (true) { Console.WriteLine("Введите команду:"); string com = Console.ReadLine(); if (com.ToLower() == "exit") { using (FileStream fs = new FileStream("person.xml", FileMode.OpenOrCreate)) { xs.Serialize(fs, parts); // Console.WriteLine("Объект сериализован"); } return; } if (com.ToLower() == "add") { string name; Console.WriteLine("Name?"); name = Console.ReadLine(); Person p = new Person(name); parts.Add(p); } if (com.ToLower() != "add") { Console.WriteLine("Доступные команды:"); Console.WriteLine("\tadd создать запись сотрудника"); Console.WriteLine("\texit Выйти и сохранить данные"); Console.ReadKey(); continue; } } } } [Serializable] public class Person { public string Name { get; set; } public Person() { } public Person(string name) { Name = name; } } } 

Hello! I'm doing a database. The console menu. With the "add" command, I add an employee (name) to the parts collection. When I exit, I serialize xml to the file person.xml. Everything is going great. But when I insert the code, so that when I run it, I check this file and deserialize it, the program breaks down. What could be the reason?

  • 3
    If you remove user interaction from code, it will be easier to understand. The minimum reproducible example is VladD
  • one
    The text of the exception will also not be superfluous. - Monk
  • 2
    "the program is breaking me" - what is this? Never (you hear? Never!) Do not indicate what error you are getting. We are so talented and perspicacious, that we will guess ourselves. - Igor

1 answer 1

Check for a file before deserializing:

  if (File.Exists("person.xml")) using (FileStream fs = new FileStream("person.xml", FileMode.OpenOrCreate)) 
  • Added and validated. Anyway exeption - Anton Evseev
  • @ AntonEvseev if an empty file has already been created in the program folder - delete it. In general, the work cycle should obviously be more difficult, but your main question was precisely this. - Monk
  • You can not delete it. I have to upload this list to newParts - Anton Evseev
  • @ AntonEvseev then the text of the exception is needed, because in this form, my code already works. - Monk
  • I also earned after deleting the file. It turns out it was damaged. Now it deserializes correctly. - Anton Evseev