C# 如何解锁被 .NET 中的进程锁定的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/242882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:31:48  来源:igfitidea点击:

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

c#temporary-filesfile-locking

提问by Pablo Retyk

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.

我希望我的应用程序清理它使用的所有临时文件,问题是并非所有临时文件都在我的控制之下,所以我只想“粗暴地”解锁它们以便以编程方式删除它们。

采纳答案by Stu Mackellar

Take a look at thisarticle. 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.

看看这篇文章。我认为即使使用互操作,您也很难在 C# 本机中执行此操作,但编写 C++/CLI 包装器程序集可能是一个很好的折衷方案。另请注意,用户需要具有 SE_DEBUG 权限才能使其工作。

回答by Ray Hayes

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!

如果您想删除所有 TEMP 文件,无论是您的应用程序拥有的文件还是其他文件,您都应该非常小心。原始应用程序可能应用了锁定,因为它想使用该文件!

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#.

如果您确实需要,您始终可以生成一个命令行应用程序,而不是尝试复制现有工具的功能,而这在 C# 中是很困难的。

回答by Travis Laborde

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.

我也一直在努力解决这个问题,最后只好用 Unlocker 的命令行实现。就我而言,它必须每天运行多次,最终每天可以毫无问题地解锁数千个文件。

回答by chilltemp

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

在 MSDN 论坛上查看此主题。有足够的信息来做你想做的事,但不推荐。