本文介绍了File.Copy之后,另一个进程正在使用该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  File.Copy(@oldPath,@newPath ); 

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


$ b如果(File.Exists(@newPath)){
File.Delete(@newPath); $ b

  
}

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

lockquote

进程无法访问文件,因为它被
使用另一个进程。b


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



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



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

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

byte [] buffer = new byte [32768];
int读取; ((read = input.Read(buffer,0,buffer.Length))> 0)

output.Write(buffer,0,read);

$ b $ catch(Exception e)
{
}
finally
{
input.Close();
input.Dispose();
output.Close();
output.Dispose();



$ div $解析方案

被另一个进程阻塞,而我没有意识到这一点。 Process Explorer确实有帮助。



典型的简单问题难以发现。

I am trying to manage files in my web application. Sometimes, I must create a file in a folder (with File.Copy):

File.Copy(@oldPath, @newPath);

And a few seconds later that file may be deleted:

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

However, I don't know why the new file remains blocked by the server process (IIS, w3wp.exe) after File.Copy. After File.Delete I get the exception:

According to the Api, File.Copy don't block the file, does it?

I have tried to release the resources but it hasn't worked. How can I resolve this?

UPDATED: Indeed, using Process Explorer the file is blocked by IIS process. I have tried to implement the copy code in order to release manually the resources but the problem still goes on:

  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();
    }
  }
解决方案

File was being blocked by another process without me being aware of it. Process Explorer was really helpful.

Typical easy issue hard to spot.

这篇关于File.Copy之后,另一个进程正在使用该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:13