Reputation: 786
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();
}
}
Upvotes: 13
Views: 17218
Reputation: 786
File was being blocked by another process without me being aware of it. Process Explorer was really helpful.
Typical easy issue hard to spot.
Upvotes: 0
Reputation: 532
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.
Upvotes: 5
Reputation: 1202
This can be caused by file indexers or anti virus software, which typically scan all new files.
Upvotes: 2