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

删除回忆录丶 提交于 2019-11-27 01:37:05

问题


This question already has an answer here:

  • Unlock Files for deletion 2 answers

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.


回答1:


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.




回答2:


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.




回答3:


Surely, of your application is wanting to clean up the temp files it owns, then you have full control to unlock these files and delete them!

If you're wanting to delete all TEMP files, whether owned by your application or otherwise, you should be VERY careful. The original application probably applied the lock because it wants to use the file!

If you truly need to, you could always spawn a command-line application rather than trying to replicate the functionality of existing tools which will be difficult in C#.




回答4:


Check out this thread on the MSDN forums. There's enough information to do what you want, but its not recommended.



来源:https://stackoverflow.com/questions/242882/how-can-i-unlock-a-file-that-is-locked-by-a-process-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!