Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File is being used by another process after File.Copy

Tags:

c#

file-io

iis

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:

"The process cannot access the file because it is being used by another process."

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();
    }
  }
like image 360
jbernal Avatar asked Aug 06 '13 08:08

jbernal


1 Answers

You can try Process Explorer to find which application opened the file handle. If Process Explorer cannot find that, use Process Monitor to trace which process is trying to access the file.

like image 200
aaron cheung Avatar answered Sep 20 '22 00:09

aaron cheung