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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With