如何避免这种`System.IO.IOException`

时间:2018-03-24 17:02:17

标签: c# text-files console-application

public static void Main()
{    
    string username = "", password, chkusername;
    bool vald, chk;
    vald = false;
    string choice = "Y";

    while (choice == "Y")
    {                        
        FileStream fs = new FileStream("Users.txt", FileMode.Append, 
            FileAccess.Write, FileShare.Read);
        StreamWriter sw = new StreamWriter(fs);
        Console.WriteLine("Enter Username : ");
        var Createnew = File.ReadAllLines("Users.txt");`
        chkusername = Console.ReadLine();
        foreach(string Dummies in Createnew)
        {
            string[] userline = Dummies.Split('#');

            if(userline[0].Equals(chkusername))
            {
                vald = true;
                Console.Clear();
                Console.WriteLine("username already exists please choose another");
                Console.ReadKey();
                Console.Clear();
                break;
            }

            chk = vald;
            if (vald == true)
            {
                Main();
            }

            while(choice == "Y")
            {
                username = chkusername;
                Console.WriteLine("Enter a Password : ");
                password = Console.ReadLine();

                sw.WriteLine(username + "#" + password);
                sw.Flush();
                sw.Close();
                fs.Close();
                Console.WriteLine("Username Created");
                Console.WriteLine("Do you want to continue ? Y/N");
                choice = Console.ReadLine();
            }
        }           
    }
}

我在这里得到一个例外:

 var Createnew = File.ReadAllLines("Users.txt");
  

System.IO.IOException:'进程无法访问该文件   'C:\用户\ ADMIN1 \源\回购\ LumberJackProgram \ LumberJackProgram \ Users.txt'   因为它正被另一个进程使用。'

1 个答案:

答案 0 :(得分:1)

首先处理在HashSet字符串集合中存储每个名称的Users.txt文件

HashSet<string> names = new HashSet<string>();
var lines = File.ReadAllLines("Users.txt");
foreach(string line in lines)
{
    string name = line.Split('#')[0];
    if(!names.Contains(name))
       names.Add(name);
}

现在您可以要求您的用户输入所需信息,并检查HashSet是否已存在名称

while (choice == "Y")
{
     Console.WriteLine("Enter Username : ");
     chkusername = Console.ReadLine();
     if(names.Contains(chkusername))
         Console.WriteLine("Name already entered");
     else
     {
        Console.WriteLine("Enter a Password : ");
        password = Console.ReadLine();
        names.Add(chkusername);

        // Write the file in append mode and close/dispose it
        using(StreamWriter sw = new StreamWriter("Users.txt",true))
            sw.WriteLine(chkusername + "#" + password);

     }
     Console.WriteLine("Continue? Y/N");
     choice = Console.ReadLine();
}

这样,您不会将读取部分与书写部分混合。如果您的文件中存在名称

,也无需重新调用Main方法来重新输入此代码