如何获取捕获特定文件的进程ID [英] How to get the process ID that catches a certain file

查看:96
本文介绍了如何获取捕获特定文件的进程ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除当前用户的临时文件夹中的所有临时文件。为此我编写了以下代码

  string  s = System.IO.Path.GetTempPath() ; 
Console.WriteLine(s);
DirectoryInfo di = new DirectoryInfo(s);
FileInfo [] fi = di.GetFiles();
foreach (FileInfo f in fi)
{
f。删除();
}



然后我遇到了一些问题,某些进程可能会使用某些文件,最后它们不会被删除,例外情况会是触发线

<前一个=c#> f.delete()



我以为我是'' d最好获取捕获每个文件并杀死它的进程ID。问题是如何获得该流程ID。



OP的附加信息来自非解决方案

当我知道捕获文件的进程时,我可以激活代表此进程的屏幕并要求用户保存/取消,或者如果后台进程我可以警告用户此进程捕获此文件和你可能会失去工作。具有此功能的程序类似于Windows执行的SHUT DOWN警告过程。

解决方案

为什么要删除正在使用的临时文件?由于你不知道这个过程对他们有什么影响,你可能会通过识别和终止这个过程而使用户失去很多工作。



为什么不检测锁定的文件,并忽略它?使用try ... catch块围绕删除并忽略异常(但一定要注释为什么忽略它!)


你可以使用Process.Id Property [ ^ ]或者 Process.GetProcesses [ ^ ]



希望它能帮到你...... :)。


我想这个是你需要的。 http://www.kartmann.org/freeware/WhoSLocking/ReadMe.htm [ ^ ]



锁定文件尝试删除的进程。他们也分享了源代码。看看那个。


I wanted to delete all temporary files in the temp folder of the current user. For this purpose I wrote the following code

string s = System.IO.Path.GetTempPath();
Console.WriteLine(s);
DirectoryInfo di = new DirectoryInfo(s);
FileInfo[] fi = di.GetFiles();
foreach (FileInfo f in fi)
{
  f.Delete();
}


I then was faced with a problem that some files may be used by some processes and finally they won''t be deleted and an exception would be trigger at the line

f.delete()


I thought that I''d better get the process ID that catches each file and kill it. The question is how to get that process id.

OP''s additional information moved from non-solution below
When I know the process that catches a file I can activate the screen that represent this process and ask the user to save/cancel , or if the process in the background I can warn the user that the this process catches this file and you may lost work. This program with this ability would be similar to the SHUT DOWN warning process that the windows do.

解决方案

Why would you want to delete temporary files which are in use? Since you do not know what the process is doing with them, you could potentially lose the user a lot of work by identifying and killing the process.

Why not just detect the locked file, and ignore it? Use a try...catch block round the delete and ignore the exception (but be sure to comment why you ignore it!)


You can use Process.Id Property[^] or else Process.GetProcesses[^]

Hope it will help you... :)


I think this is what you need. http://www.kartmann.org/freeware/WhoSLocking/ReadMe.htm[^]

The process who locked your file trying to delete. they have share the source code too. have a look at that.


这篇关于如何获取捕获特定文件的进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆