我该如何修复'System.IO.IOException:'进程无法访问文件'

时间:2019-09-15 18:31:46

标签: c#

我想知道如何在没有System.IO.IOException的情况下删除文件 它一直在说 “ System.IO.IOException:'该进程无法访问文件'C:\ A1 \ AccNum.txt',因为它正在被另一个进程使用。'

       private static void deleteaccount()
       {
        int accountNum2;
        string accountVar = string.Empty;
        const int MaxLength = 10;
        string line2;

        Console.WriteLine("DELETE AN ACCOUNT");
        Console.WriteLine("=================");
        Console.WriteLine("ENTER THE DETAILS");
        Console.WriteLine("");
        Console.WriteLine("Account Number: {0}", accountVar);
        accountVar = Console.ReadLine();
        Console.WriteLine("=================");

        try
        {
            accountNum2 = Convert.ToInt32(accountVar);
        }
        catch (OverflowException ex)
        {
            Console.WriteLine("The Error is {0}: ", ex);
        }
        finally
        {
            if (accountVar.Length < MaxLength && accountVar.Length > 5)
            {
                System.IO.StreamReader file = new System.IO.StreamReader(@"C://A1//AccNum.txt");
                while ((line2 = file.ReadLine()) != null)
                    if (line2.Contains(accountVar))
                    {
                        Console.WriteLine("Account Found! Details display below...");
                        string text2 = File.ReadAllText(@"C://A1//AccNum.txt");
                        Console.WriteLine(text2);
                        Console.WriteLine("=================");
                        Console.WriteLine("");
                        Console.Write("Delete? (y/n): ");
                        string answer2;
                        answer2 = Console.ReadLine();
                        if ((answer2.Contains("y") || answer2.Contains("Y")))
                        {
                            if (File.Exists(@"C://A1//AccNum.txt"))
                            {
                                File.Delete(@"C://A1//AccNum.txt"); // This part says it has 'System.IO.IOException: 'The process cannot access the file 'C:\A1\AccNum.txt' because it is being used by another process.''
                            }

                            Console.Write("Account Deleted!...");
                            Console.Read();
                            ShowMainMenu();
                            break;
                        }

2 个答案:

答案 0 :(得分:1)

您正在使用文件(使用阅读器),除非停止使用,否则无法将其删除。

在if块内关闭阅读器,然后尝试删除该文件。

使用File.ReadAllText时,不需要关闭任何内容(以及在File的其他静态成员中),但对于StreamReader,则需要自己关闭流。

P.s您还应该重构代码,因为它有缺陷。

答案 1 :(得分:1)

AccNum.txt文件由您的代码打开两次。在打开文件时,同时尝试删除触发IOException的文件。

如果要删除文件,请确保没有其他程序打开文件。您尚未打开要删除的文件的文件句柄。在您的程序中,您就是在删除文件的同时打开文件的人。因此,请首先释放文件句柄。

 if (File.Exists(@"C://A1//AccNum.txt"))
 {
     // file is your StreamReader.
     file.Close();
     file.Dispose();
     File.Delete(@"C://A1//AccNum.txt"); 
 }

还要注意,如果在文件中找到accountVar,则将打开同一文件2次或多次。更好的选择是坚持使用单个File.ReadAllText()通话并使用该内容。