Deserylization from the collection. C#



  • 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 menu is console. I'm adding a staff member to the collaboration parts. With "exit" on the xml

    in person.xml. Everything's going great. But when I put in a code to get this file checked in on the launch, and his desserization broken my program. What's the reason?



  • Check if you have a file before desservation:

      if (File.Exists("person.xml"))
      using (FileStream fs = new FileStream("person.xml", FileMode.OpenOrCreate))
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2