即使使用 using 语句,文件也被另一个进程锁定

File locked by another process even with using statement

我正在尝试写入一个名为 output.txt 的文件。我的代码第一次运行没问题,但第二次抛出异常:

The process cannot access output1.txt because it is being used by another process

但我在 using 语句中使用了它,它应该被处理掉并且文件应该被解锁。

构造函数说 if the file exists, it can either be appended to or overwritten。似乎没有这样做,因为它抛出了 IOException。

为什么会这样?

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@directoryURL + "\output"+outputNumber+".txt", true))
{
    foreach (string line in splitOutput)
    {
        file.WriteLine(line);
    }
}

文件仍然被锁定的原因有很多,例如病毒扫描程序。

Use SysInternals Process Explorer, "Find Handle" (Ctrl+F),输入你的文件名,看哪个应用程序正在使用您的文件。

您已将 urltest.vshost.exe 确定为罪魁祸首(在评论中提到),因此它一定是您的代码...

在 PasteBin 提供的代码中,我看到了以下循环

foreach (string file in fileEntries)
{
    StreamReader fileStream = new StreamReader(file);
    ...
    FileHander(fileStream, extension, websiteURL, fileName);
}

这会打开许多​​文件流,但 FileHandler() 仅对某些扩展名起作用:

private void FileHander(StreamReader fileStream, string extension, string websiteURL, string fileName)
{
    switch (extension)
    {
        ...
        CheckPowershell(fileStream, websiteURL, fileName);
        ...
    }
} 

并且只有 CheckPowershell() 关闭文件:

private void CheckPowershell(StreamReader fileStream, string websiteURL, string fileName)
{
    ...
    fileStream.Close();
}

因此所有没有特定扩展名(例如 .txt)的文件都保持打开状态。

一个快速的解决方案似乎是将 Close()CheckPowershell() 移动到 FileHander()。更专业的方法需要更多的重构。