Faced such a problem. There is a class User . It has a SaveUser method that writes only 1 entry to the file. There is a LoadUsers method that returns a list of all users written to the file. An error occurs in the line with the comment. It cannot convert User to User []. How to solve this problem without rewriting the SaveUser method?

 class User { private string name; private string password; private string key; private static string fileName = @"Data\users.dat"; public void SaveUser() { BinaryFormatter formatter = new BinaryFormatter(); // получаем поток, куда будем записывать сериализованный объект using (FileStream fs = new FileStream(fileName, FileMode.Append)) { formatter.Serialize(fs, this); } } public static List<User> LoadUsers() { List<User> listUser = new List<User>(); BinaryFormatter formatter = new BinaryFormatter(); //десериализация из файла people.dat using (FileStream fs = new FileStream(fileName, FileMode.Open)) { if (fs == null) return listUser; else { User[] deserilizeUsers = (User[])formatter.Deserialize(fs);// ошибка, нельзя преобразовать User в User[] foreach (User user in deserilizeUsers) { listUser.Add(user); } } } return listUser; } } 
  • If users wrote to the file one by one, then they should be read one by one! In a loop until the file ends. - Pavel Mayorov
  • Better yet, discover SQLite or at least XML serialization. With binary serialization still cry. - Pavel Mayorov
  • the file should not be understandable when opened by the editor. Binary is best suited - Alexandr
  • If you think that there are no editors for binary serialized data, you are mistaken. It is better to encrypt the file than to rely on the incomprehensibility of the format. But keep in mind that encryption is also opened by a specialist. - Pavel Mayorov
  • Pavel Mayorov unless at start will not be fully accessible in open form all the contents of SQLite? - codename0082016

1 answer 1

As already stated in the comment, you need to deserialize the records one by one, in a loop. Like that:

 List<User> listUser = new List<User>(); BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { while (fs.Position < fs.Length) { var user = (User)formatter.Deserialize(fs); listUser.Add(user); } } return listUser; 

Of course, you need to add exception handling.