简体   繁体   English

C#异常 - 无法访问文件,因为它正由另一个进程使用

[英]C# Exception - File cannot be accessed because it is being used by another process

I have a Windows Forms Application that uses 2 forms, with both writing to separate files (file paths given by inclusion of strings in textboxes on the form). 我有一个Windows窗体应用程序,它使用2个窗体,同时写入单独的文件(通过在窗体上的文本框中包含字符串给出的文件路径)。

For form1, I have a number of functions that write data to the file on various different button clicks. 对于form1,我有许多函数可以通过各种不同的按钮点击将数据写入文件。 This being the case, I used the StreamWriter consoleFile = new StreamWriter(File.OpenWrite(fileName)); 在这种情况下,我使用了StreamWriter consoleFile = new StreamWriter(File.OpenWrite(fileName)); method for the first writing to file and StreamWriter consoleFile = File.AppendText(fileName); 第一次写入文件的方法和StreamWriter consoleFile = File.AppendText(fileName); for any subsequent ones. 任何后续的。 This has worked fine. 这很好。

When it came to implementing the same feature for Form2, the main difference is that all the text is written at once (one function containing four sub-functions to try and keep the code tidy). 在为Form2实现相同功能时,主要区别在于所有文本都是一次写入的(一个函数包含四个子函数,以尝试保持代码整洁)。 I went about it like this... 我这样做了......

    public void writeChecklistToFile()
    {
        //open new file for writing
        StreamWriter checklistFileStart = new StreamWriter(File.OpenWrite(getChecklistFile()));
        checklistFileStart.WriteLine("Pre-Anaesthetic Checklist\n");

        //sub-functions (one for each section of list)
        //append tool used in separate functions
        //StreamWriter checklistFile = File.AppendText(getChecklistFile());
        writeAnimalDetails();
        writeAnimalHistory();
        writeAnimalExamination();
        writeDrugsCheck();
    }

Each of the sub-functions then contains the appendText variable shown above: 然后每个子函数都包含上面显示的appendText变量:

    public void writeAnimalDetails()
    {
        StreamWriter checklistFile = File.AppendText(getChecklistFile());

        //...
    }

Whenever I click the button that calls the main function, it throws an exception on the first File.AppendText() method. 每当我单击调用main函数的按钮时,它就会在第一个File.AppendText()方法上抛出异常。 It states that the destination file cannot be accessed because it is already being used in another process. 它指出无法访问目标文件,因为它已在另一个进程中使用。

Presumably this has to be the OpenWrite() as it is not used anywhere before that, but I don't understand why this error would occur in my form2 when it doesn't in form1! 据推测,这必须是OpenWrite(),因为它在此之前没有被使用过,但是我不明白为什么当我的form2不在form1中时会出现这个错误!

If anyone could help me get around this, or can point me in the direction of an easier way to do it, I'd really appreciate that. 如果有人能帮助我解决这个问题,或者可以指出我更方便的方法,我真的很感激。

Thanks 谢谢

Mark 标记

Read the error as "File cannot be accessed because [the file is still open for use by this] process ". 将错误读取为“因为[文件仍然打开以供此处使用]进程,因此无法访问文件 ”。

The problem is that the file resource - from File.OpenWrite - is not being Disposed correctly and an unmanaged file handle, with an exclusive lock, is kept open . 问题是,该文件的资源-从File.OpenWrite -没有被处理完毕正常和非托管的文件句柄,以一个排他锁,保持开放 This in turn results in exceptions when trying to open the still-open file for writing. 当试图打开仍然打开的文件进行写入时,这又会导致异常。 Use the using statement to help with lifetime management, as discussed here . 使用using语句来帮助进行生命周期管理, 如此处所述

In this particular case I recommend supplying the StreamWriter - created once - as an argument to the functions that need to write to it and then Dispose the entire open file resource once at the end when complete. 在这种特殊情况下,我建议提供StreamWriter - 一次创建 - 作为需要写入它的函数的参数,然后在完成时将整个打开文件资源放在一端。 This ensures a more visible resource lifetime and avoids several open-close operations. 这确保了更明显的资源生命周期并避免了几次开闭操作。

public void writeChecklistToFile()
{
   // Open file for writing once..
   using (var checklistWriter = new StreamWriter(File.OpenWrite(getChecklistFile())))
   {
      // .. write everything to it, using the same Stream
      checklistWriter.WriteLine("Pre-Anaesthetic Checklist\n");
      writeAnimalDetails(checklistWriter);
      writeAnimalHistory(checklistWriter);
      writeAnimalExamination(checklistWriter);
      writeDrugsCheck(checklistWriter);
   }
   // And the file is really closed here, thanks to using/Dispose
}

Also see 另见

I think the reason it works in your first form is that you only ever have one StreamWriter existing at a time. 我认为它以你的第一种形式工作的原因是你一次只能存在一个StreamWriter。 You click a button, a StreamWriter is created, the function ends, and the StreamWriter is automatically closed before the next button click calls a function. 单击按钮,创建StreamWriter,函数结束,StreamWriter在下一次按钮单击调用函数之前自动关闭。

With your second form, however, you're calling your sub functions with their StreamWriters within a main function that also has a StreamWriter. 但是,使用第二种形式,您将在具有StreamWriter的主函数中使用StreamWriters调用子函数。 What that amounts to is you have more than one StreamWriter trying to open the file at the same time, and thus the error. 相当于你有多个StreamWriter试图同时打开文件,从而错误。

To fix this, you can put after your call to WriteLine in your writeChecklistToFile function: 要解决此问题,您可以在writeChecklistToFile函数中调用WriteLine之后:
checklistFileStart.Close(); checklistFileStart.Close();

This will close your first FileStream, and allow your subsequent ones to open up the file. 这将关闭您的第一个FileStream,并允许您的后续文件打开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法访问该文件,因为它正在被另一个进程c#使用 - The file cannot be accessed because it is being used by another process c# C#文件异常:由于其他进程正在使用该文件,因此无法访问该文件 - C# File Exception: cannot access the file because it is being used by another process c#无法访问文件,因为它正被另一个进程使用 - c# Cannot access file because it is being used by another process 无法访问文件,因为它正在被另一个进程使用 - File cannot be accessed because it is being used by another process 无法访问文件,因为它被另一个进程异常使用 - File cannot be accessed because it is used by another process exception 无法访问该进程,因为它正由另一个进程使用 - The process cannot be accessed because it's being used by another process C# File.ReadAllText 进程无法访问该文件,因为它正被另一个进程使用 - C# File.ReadAllText The process cannot access the file because it is being used by another process IOException:该进程无法访问文件“文件路径”,因为它正在被C#控制台应用程序中的另一个进程使用 - IOException: The process cannot access the file 'file path' because it is being used by another process in Console Application in C# 生成 txt 文件时出现“进程无法访问文件 --- 因为它正被另一个进程使用” C# - "The process cannot access the file --- because it is being used by another process" when making txt file C# 该进程无法访问文件'D:.txt',因为它正在由c#中的另一个进程使用 - The process cannot access the file 'D:.txt' because it is being used by another process in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM