Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a file which is locked by another process in C#?

I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using File.Delete().

like image 655
Dean Bates Avatar asked Aug 04 '08 05:08

Dean Bates


People also ask

How do I close a locked file?

Select the locked file or folder and you'll see the handle in the details box at the bottom of the Process Explorer window. Right-click the handle and select “Close Handle.” If multiple processes are listed in the search window, you'll have to repeat this step to close the handle for each process.


1 Answers

Killing other processes is not a healthy thing to do. If your scenario involves something like uninstallation, you could use the MoveFileEx API function to mark the file for deletion upon next reboot.

If it appears that you really need to delete a file in use by another process, I'd recommend re-considering the actual problem before considering any solutions.

like image 194
Ishmaeel Avatar answered Sep 24 '22 12:09

Ishmaeel