How can I delete a file that is in use by another process?

Suresh Chaudhary picture Suresh Chaudhary · Mar 8, 2011 · Viewed 49.6k times · Source

When I try to delete a file occurs the following exception:

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

My code looks like:

string[] files = Directory.GetFiles(@"C:\SEDocumentConverter\SOURCE");
foreach (string file in files)
{               
   File.Delete(file);
}

How can I solve this problem?

Answer

Cody Gray picture Cody Gray · Mar 8, 2011

There is no way to delete a file that's currently being used by another process. You have to close whatever program has that file open first, before you can delete it.

If you don't already know which program that is, you can figure it out using Handle or Process Explorer.