我以前能够使用C#应用程序(网络表单)从bin文件进行读写。进行一些更改后,我仍然可以写但不能读多个用户。
我使用了调试器。即使文件中有2个用户,foreach循环也仅从序列化中计算1个用户。它是一个静态列表。它曾经工作过。我不知道我做错了什么。
```
format = new BinaryFormatter();
Users = new List<User>();
try
{
flux = new FileStream(path, FileMode.Open, FileAccess.Read);
}
catch
{
Users.Add(new User("root", "root123", "[email protected]", "Administrator"));
Users.Add(new User("user", "user123", "[email protected]", "User"));
Save(path);
}
finally
{
Users = (List<User>)format.Deserialize(flux);
if (flux != null)
flux.Close();
}
foreach (User account in Serialization.Users)
{
if (account.Username == username.Text && account.Password == password.Text)
return true;
}
return false;
```
我应该能够用第二个用户登录,但是正如我提到的,foreach循环在1次迭代后停止并返回false。我不明白为什么。
我发现我的代码出了什么问题。问题不是我的try / catch,而是新用户创建帐户时的问题。正确登录并通过断开连接返回首页后,Page_Load()不会再次读取我的二进制文件,因为我忘记了在那里反序列化。