Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unlock a file that is locked by a process in .NET [duplicate]

I want my application to clean all the temp files it used, the problem is that not all the temp files are under my control, so I just want to "brutally" unlock them in order to delete them programatically.

like image 423
Pablo Retyk Avatar asked Oct 28 '08 10:10

Pablo Retyk


People also ask

How do you copy a file that is being used by another process?

To create a copy of a file that is read- and/or write-locked by another process on Windows, the simplest (and probably only) solution is to use the Volume Shadow Copy Service (VSS). The Volume Shadow Copy Service is complex and difficult to call from managed code.


2 Answers

Take a look at this article. I think that you'll struggle to do this in C# natively, even using interop, but writing a C++/CLI wrapper assembly may be a good compromise. Note also that the user needs to have the SE_DEBUG privilege for this to work.

like image 113
Stu Mackellar Avatar answered Sep 29 '22 18:09

Stu Mackellar


I've struggled with this as well, and ended up just shelling out to Unlocker's command line implementation. In my case it has to run many times daily and ends up unlocking thousands of files per day without any problem.

like image 31
Travis Laborde Avatar answered Sep 29 '22 18:09

Travis Laborde