编辑文本文件中的字符串后,无法读取文件中的行

时间:2019-05-04 10:21:18

标签: c#

假定EditUser方法正在编辑文本文件中的字符串。问题是,在文本文件中编辑了字符串之后,ReadUser方法将不再能够读取文本文件。如何解决这个问题?

文本文件中的示例字符串: 123 123 444 444

在文本文件中编辑字符串后: 222 222 333 333

代码如下所示:


public void ReadUser()
        {
            int i = 0;
            user = UserID;
            password = Password;

            using (StreamReader sr = new StreamReader(File.Open("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt", FileMode.Open)))
            {
                string line;
                bool match = false;
                while ((line = sr.ReadLine()) != null)
                {
                    if (i % 2 == 0)
                    {
                        user1 = line;
                    }
                    else if (i % 2 == 1)
                    {
                        password1 = line;
                    }
                    if (user == user1 && password == password1)
                    {
                        Console.WriteLine("Login Successful");
                        match = true;
                        break;
                    }
                    i++;
                }
                if (match == false)
                {
                    Console.WriteLine("Login Failed");
                }
                sr.Close();
            }
        }

public void EditUser(string currentUserID, string newCurrentUserID, string currentPassword, string newCurrentPassword)
        {

            StreamReader sr = new StreamReader("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt");
            string[] rows = Regex.Split(sr.ReadToEnd(), "\n");
            sr.Close();

            StreamWriter sw = new StreamWriter("C:\\Users\\user\\Documents\\Projects\\AdministratorModule//userTextFile.txt");
            for (int i = 0; i < rows.Length; i++)
            {
                if (rows[i].Contains(currentUserID))
                {
                    rows[i] = rows[i].Replace(currentUserID, newCurrentUserID);
                }
                if (rows[i].Contains(currentPassword))
                {
                    rows[i] = rows[i].Replace(currentPassword, newCurrentPassword);
                }
                sw.WriteLine(rows[i]);
            }


            sw.Close();

        }

0 个答案:

没有答案