Adam
Adam

Reputation: 75

C# Windows Forms Binary File

I have a method that is called when a user resets his password. When it is executed, it should see if the user exists in the binary file "PlayerDetails.bin".

The code works as intended and the password is reset, but an error is thrown despite this:

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();
            }
        }
    }
}

Upvotes: 2

Views: 997

Answers (1)

dko
dko

Reputation: 718

move the st.Close(); st.Dispose() out of the while loop.

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();
        }
    }
}

Upvotes: 3

Related Questions