Click here to Skip to main content
14,694,012 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am uploading a excel file to insert the record into table. I am saving the file on server to insert the record and my all records are successfully uploaded. After the uploading the file i want to delete the file from saved location but when i trying to delete the file an error occur "The file is being used by another process".

try
{                   
   System.IO.File.Delete(tPath);
}
catch (System.IO.IOException ex)
{
   Console.WriteLine(ex.Message); 
}



Please help how i can do it?
Posted
Updated 12-Feb-14 3:53am
v2

You can't delete the file for very good reasons. Suppose that an accounting process is busy reading from the file to create ledger entries and you take the file out from underneath them - all of a sudden the ledger will not balance. In this case, Windows is trying to protect you.

If you must delete the file, then theoretically you could issue a DEL filename command (the equivalent of calling DEL at the command prompt) through Process.Start. The alternative is to kill the lock on the file using a much more complex process which involves a lot of p/invoking.
   
Comments
Sergey Alexandrovich Kryukov 12-Feb-14 13:04pm
   
All correct, a 5.
I added more useful information to it. OP cannot delete the file, but can take care about the situation. Please see my answer.
—SA
you cannot. when a file is open, it is locked by os. you cannot rename, delete, move that file. As I understand, you don't close that file after using it. first close file and all references to it, then you can delete it.
   
v2
You cannot delete such files, but you can take care about it. Please see my past answer:
File used by another process exception[^].

—SA
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900