12

我正在尝试管理我的 Web 应用程序中的文件。有时,我必须在文件夹中创建一个文件(使用 File.Copy):

File.Copy(@oldPath, @newPath);

几秒钟后,该文件可能会被删除:

if (File.Exists(@newPath)) {
  File.Delete(@newPath);            
}

但是,我不知道为什么新文件在 File.Copy 之后仍然被服务器进程(IIS、w3wp.exe)阻止。在 File.Delete 之后,我得到了异常:

“该进程无法访问该文件,因为它正被另一个进程使用。”

根据 Api,File.Copy 不会阻止文件,是吗?

我试图释放资源,但没有奏效。我该如何解决这个问题?

更新: 确实,使用 Process Explorer 文件被 IIS 进程阻止。我试图实现复制代码以手动释放资源,但问题仍然存在:

  public void copy(String oldPath, String newPath)
  {
    FileStream input = null;
    FileStream output = null;
    try
    {
      input = new FileStream(oldPath, FileMode.Open);
      output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite);

      byte[] buffer = new byte[32768];
      int read;
      while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
      {
        output.Write(buffer, 0, read);
      }
    }
    catch (Exception e)
    {
    }
    finally
    {
      input.Close();
      input.Dispose();
      output.Close();
      output.Dispose();
    }
  }
4

3 回答 3

4

您可以尝试Process Explorer来查找打开文件句柄的应用程序。如果 Process Explorer 找不到,请使用Process Monitor跟踪哪个进程正在尝试访问该文件。

于 2013-08-06T09:05:28.137 回答
2

这可能是由文件索引器或防病毒软件引起的,它们通常会扫描所有新文件。

于 2013-08-06T08:41:05.427 回答
0

文件在我不知道的情况下被另一个进程阻止。Process Explorer 真的很有帮助。

典型的容易发现的问题。

于 2015-08-11T18:13:04.673 回答