如何获取当前运行进程的文件名?

本文关键字:进程 运行 文件名 何获取 获取 | 更新日期: 2023-09-27 18:06:01

我是这样得到所有的工作过程的:

Process[] processlist = Process.GetProcesses();
foreach (Process theprocess in processlist)
{
      listBox1.Items.Add(theprocess.ProcessName);
}

我是这样得到一个目录下的文件的:

foreach (System.IO.FileInfo file in dir.GetFiles())
{
}

我想要得到每个进程目录下的文件。这是我使用的方法:

ListView listView1;
ImageList imageList1;
public void ExtractAssociatedIconEx()
{
    listView1 = new ListView();
    imageList1 = new ImageList();
    listView1.Location = new Point(37, 12);
    listView1.Size = new Size(151, 262);
    listView1.SmallImageList = imageList1;
    listView1.View = View.SmallIcon;
    this.ClientSize = new System.Drawing.Size(292, 266);
    this.Controls.Add(this.listView1);
    this.Text = "Form1";
    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"c:'");
    ListViewItem item;
    listView1.BeginUpdate();

    foreach (System.IO.FileInfo file in dir.GetFiles())
    {
        Icon iconForFile = SystemIcons.WinLogo;
        item = new ListViewItem(file.Name, 1);
        iconForFile = Icon.ExtractAssociatedIcon(file.FullName);
        if (!imageList1.Images.ContainsKey(file.Extension))
        {           
            iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName);
            imageList1.Images.Add(file.Extension, iconForFile);
        }
        item.ImageKey = file.Extension;
        listView1.Items.Add(item);
    }
    listView1.EndUpdate();
}

但是,我想获得当前运行进程的图标,而不是只获得C:'文件的图标。

如何获取当前运行进程的文件名?

基于此:

foreach (Process in Process.GetProcesses())
{
    string filePath = process.Modules[0].FileName;
    Icon fileIcon = Icon.ExtractAssociatedIcon(filePath);
    ...
}