【问题标题】:C# Get all executables from directory structure, then kill if runningC# 从目录结构中获取所有可执行文件,然后在运行时终止
【发布时间】:2017-10-03 08:41:18
【问题描述】:

我正在尝试:

1) 获取目录和所有子目录中所有可执行文件的列表。

2) 如果这些可执行文件中的任何一个正在运行,则终止该进程。

到目前为止我所拥有的:

String[] exes =
Directory.GetFiles("C:\\Temp", "*.EXE", SearchOption.AllDirectories)
.Select(fileName => Path.GetFileNameWithoutExtension(fileName))
.ToArray();

{
    exes.ToList().ForEach(Console.WriteLine);
}

Console.ReadLine();

所以这向我显示了可执行文件的列表。如果进程正在运行,我如何使用此列表来终止进程?

【问题讨论】:

  • 如果(主/任何)模块的路径在该目录结构中,您是否应该不转而枚举所有进程并杀死它们?是否有理由希望/不期望可能运行的 exe 已从该目录加载了一个 DLL,但该进程应免于杀死?
  • 我以stackoverflow.com/questions/3899864/what-process-locks-a-file为基础重写了windows的fuser ..允许你迭代给定文件的进程,通过一些tweeking你可以改变它来处理你从中获得的一些文件你的文件列表
  • @Damien_The_Unbeliever 我只是在学习 C#,所以请原谅我的无知。为什么这样会更好?在代码方面看起来会如何?

标签: c#


【解决方案1】:

这样结束了:

                    try
                {
                    //Find exes in dir and subdirs
                    String[] exes =
                    Directory.GetFiles("C:\\Temp", "*.EXE", SearchOption.AllDirectories)
                    .Select(fileName => Path.GetFileNameWithoutExtension(fileName))
                    .AsEnumerable()
                    .ToArray();

                    // kill the process if it is in the list 
                    var runningProceses = Process.GetProcesses();
                    for (int i = 0; i < runningProceses.Length; i++)
                    {

                     if (exes.Contains(runningProceses[i].ProcessName))
                     {
                      runningProceses[i].Kill(); 
                     }

                    }


                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多