关闭并重新打开程序后尝试打开文件时出现文件访问异常

时间:2018-01-18 11:49:00

标签: c# exception file-access

我似乎遇到了一些用于更改用户软件密码的代码的问题。如果您运行该软件并更改密码,它将首次成功,但是,如果用户随后注销(重新启动软件),然后再次尝试更改其密码,则会引发文件访问异常。

软件重启后怎么会出现这种情况?

代码:

void ChangePassword()
    {
        string UserDataBaseString = File.ReadAllText("UserData.txt");
        string[] UserDataBase = File.ReadAllLines("UserData.txt");
        if (UserDataBaseString.Contains(MD5Hash(NewPassworTxBx.Text)))
        {
            MessageBox.Show("That password is already in use");
        }
        else
        {
            int i = 0;
            while (i != UserDataBase.Length)
            {
                MessageBox.Show(UserDataBase[i]);
                if (UserDataBase[i].ToString() == GlobalVar.UserNameEntered.PadRight(20, ' ') + MD5Hash(CurrentPasswordTxBx.Text))
                {

                    string usr = UserDataBase[i].Substring(0, 20);
                    string input = usr + MD5Hash(NewPassworTxBx.Text);
                    UserDataBase[i] = input;
                    MessageBox.Show(UserDataBase[i].ToString());
                    //File.WriteAllLines("UserData.txt", UserDataBase);
                    int i1 = 0;

                    using (var writer = new StreamWriter("UserData.txt", false))
                    {
                        while (i1 != UserDataBase.Length)
                        {
                            writer.WriteLine(UserDataBase[i1]);
                            i1 = i1 + 1;
                        }
                    }
                    MessageBox.Show("Password changed to: " + NewPassworTxBx.Text);
                    break;
                }
                i = i + 1;
            }
        }
    }

0 个答案:

没有答案