Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# File.Copy之后的另一个进程正在使用文件_C#_Iis_File Io - Fatal编程技术网

C# File.Copy之后的另一个进程正在使用文件

C# File.Copy之后的另一个进程正在使用文件,c#,iis,file-io,C#,Iis,File Io,我正在尝试管理web应用程序中的文件。有时,我必须在文件夹中创建文件(使用file.Copy): 几秒钟后,该文件可能会被删除: if (File.Exists(@newPath)) { File.Delete(@newPath); } 但是,我不知道为什么新文件在file.Copy之后仍然被服务器进程(IIS、w3wp.exe)阻止。在File.Delete之后,我得到一个异常: “进程无法访问该文件,因为它正由用户使用 另一个过程。” 根据Api,File.Co

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

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

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();
    }
  }

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

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

文件被另一个进程阻止,而我没有意识到它。Process Explorer真的很有帮助


典型的容易发现的问题

那么,文件的用途是什么?显然,您不会只是毫无意义地创建一个文件,而其他任何东西都不会在几秒钟后将其删除,所以一定有什么东西在使用它。那是什么东西?文件来自另一个系统,所以,它在其中被更改了,我必须替换旧的。我正在开发一个“镜像”系统。也许这个类似的问题可能会对您有所帮助:@Bridge
File.Copy()
将始终完成并关闭文件句柄,然后再返回。@jbernal:也许文件的某个地方还有句柄?您是否以任何方式处理该文件?也许那个物体还在记忆中?封锁是否永远持续,而不重新启动IIS?当然,这是一个选项,但需要多少时间?我已等待了几分钟,但文件仍被阻止。您可以从系统内部尝试。使用“查找句柄或DLL”功能将显示哪些进程在文件上有打开的句柄。非常有用的程序。我使用过它,事实上唯一使用该文件的进程是w3wp.exe(IIS)。我将用streams实现copy函数,以便显式地编写close()或dispose()语句。
  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();
    }
  }