我需要杀死特定文件上的所有Microsoft Word进程

我有一个通宵工作,可以打开文件并进行编辑,然后再次关闭。

private void killprocess(string p)
{
    foreach (Process proc in Process.GetProcessesByName(p).OrderBy(x=>x.Id))
    {
        proc.Kill();
    }
}


此方法杀死具有特定名称的所有进程,在这种情况下为p =“ winword”
但是...我想杀死所有进程,其中p =“ winword”和FilePath =“ C:\ Temp \ Test.docx”。有任何想法吗?

最佳答案

如果用户双击该文件并打开WinWord,则它将作为命令行传递。

您可以尝试以下方法:

private static void Killprocess(string processName, string expectedCommandLine)
{
    foreach (Process proc in Process.GetProcessesByName(processName).OrderBy(x => x.Id))
    {
        var commandLine = GetCommandLine(proc);
        if (commandLine.Contains(expectedCommandLine))
        {
            proc.Kill();
        }
    }
}

private static string GetCommandLine(Process process)
{
    string wmiQuery = string.Format("select CommandLine from Win32_Process where ProcessId={0}", process.Id);
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
    ManagementObjectCollection result = searcher.Get();
    return result.Cast<ManagementObject>()
        .Select(x => x["CommandLine"].ToString())
        .FirstOrDefault();
}

private static void Main()
{
    Killprocess("winword", yourfullFilePath);
}


注意:如果用户通过菜单打开文件,则需要做更多的工作。 You need to find whether a process(Winword) has open file handle to the file您正在担心。一旦发现可以杀死它。

10-05 21:12
查看更多