【问题标题】:Identifying process handles and locks on files in managed code识别托管代码中文件的进程句柄和锁定
【发布时间】:2009-09-11 12:37:49
【问题描述】:

我正在使用 DotNetZip 库将文件压缩到一个文件夹中。为了识别当前由其他进程打开的文件,我使用了来自 SysInternals.com 的“handle.exe”。我通过使用参数调用它并解析输出来做到这一点。

using (Process handleProcess = new Process())
{
    // -- Set up the parameters and call the process.
    handleProcess.StartInfo.FileName = "handle.exe";
    handleProcess.StartInfo.UseShellExecute = false;
    handleProcess.StartInfo.RedirectStandardOutput = true;
    handleProcess.StartInfo.Arguments = "-u " + fileName;
    handleProcess.Start();
...

这很有效,但有一种杂乱无章的感觉。任何人都可以在托管代码中提出更好的方法吗?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    以下代码显示了其他进程打开的文件:

    SelectQuery query = new SelectQuery("select name from cim_datafile");
    using (ManagementObjectSearcher searcher = new
    ManagementObjectSearcher(query))
    {
        foreach (ManagementObject mo in searcher.Get())
        {
            Console.WriteLine("File Name: {0} \nIs currently opened", mo.Properties["Name"].Value);
        }
    }
    

    它是this的略微修改版本。

    【讨论】:

      【解决方案2】:

      See the answers in a similar question asked on SO。在另一个问题using interop was suggested(还有其他人建议使用 SysInternals)。

      无论做什么,都需要有重试逻辑。我之前写过适配器,不得不重试。重试逻辑本身被封装在一个 RetryTracker 类中,其中包含用于不同算法(例如线性延迟、步进延迟等)的子类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-17
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多