C# Windows 窗体二进制文件

标签 c# binaryfiles

我有一个在用户重置密码时调用的方法。执行时,它应该查看用户是否存在于二进制文件“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/

相关文章:

c# - C# 中的引用和对象

c++ - 在不使用 ignore() 的情况下读取二进制文件(C++)时忽略 N 个字节?

c# - 如何处理多个 Enumerable.Zip 调用?

c# - 从单独的进程中自动化 Visual Studio 实例

linux - 比较二进制文件并仅打印匹配行的偏移量

python - 阻止在python中读取文件

node.js - 如何压缩十进制存储值。如何为变量类型PIC S9(09)V99 COMP-3的压缩十进制编写 Node js逻辑

c++ - 无法输出到 C++ 中的二进制文件

javascript - 正则表达式限制小数点后两位

c# - 如何为名称中带有空格的列创建复杂数据类型?