The file is used by another process after File.Copy.

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

File.Copy(@oldPath, @newPath); 

And after a few seconds this file can be deleted:

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

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

"The process cannot access the file because it is using a different process."

According to Api, File.Copy does not block the file, does it?

I tried releasing resources, but it did not work. How can i solve this?

UPDATED: In fact, using Process Explorer, the file is blocked by the IIS process. I tried to implement copy code to free resources manually, but the problem still continues:

  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(); } } 
+7
c # file-io iis
source share
3 answers

The file was blocked by another process, not knowing about it. Process Explorer was really helpful.

A typical simple question is difficult to determine.

0
source share

You can try Process Explorer to find which application opened the file descriptor. If Process Explorer cannot find this, use Process Monitor to track which process is trying to access the file.

+3
source share

This can be caused by file indexers or antivirus software that usually scans all new files.

+2
source share

All Articles