我有一个在用户重置密码时调用的方法。执行时,它应该查看用户是否存在于二进制文件“PlayerDetails.bin”中。
代码按预期工作并且密码已重置,但尽管如此仍会抛出错误:
An unhandled exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll. Additional information: Cannot access a closed file.
public static bool ResetPassword(string username, string password)
{
//open file for read and write
long pos = -1;
bool found = false;
Player readPlayer;
Stream st;
try
{
st = File.Open("PlayerDetails.bin", FileMode.Open, FileAccess.ReadWrite);
BinaryFormatter bf = new BinaryFormatter();
while (st.Position < st.Length && !found)
{
pos = st.Position;
readPlayer = (Player)bf.Deserialize(st);
if (readPlayer.username.CompareTo(username) == 0)
{
found = true;
readPlayer.password = password;
st.Seek(pos, SeekOrigin.Begin);
bf.Serialize(st, readPlayer);
st.Close();
st.Dispose();
}
}
}
}
最佳答案
移动 st.Close(); st.Dispose()
退出 while 循环。
Stream st= null;
try
{
st = File.Open("PlayerDetails.bin", FileMode.Open, FileAccess.ReadWrite);
BinaryFormatter bf = new BinaryFormatter();
try
{
while (st.Position < st.Length && !found)
{
pos = st.Position;
readPlayer = (Player)bf.Deserialize(st);
if (readPlayer.username.CompareTo(username) == 0)
{
found = true;
readPlayer.password = password;
st.Seek(pos, SeekOrigin.Begin);
bf.Serialize(st, readPlayer);
}
}
}
finally
{
if(st != null)
{
st.Close();
st.Dispose();
}
}
}
关于C# Windows 窗体二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149195/