我创建了一个应用程序,用于在计算机上记录用户的活动历史记录。目前,我需要找出在Word中打开的文件路径(例如с:\documents\FileName.docx
)。我刚刚知道了EXE文件的路径。我有进程ID,但在ManagementObject
我没有找到任何有关可执行文件路径的信息。我怎样才能做到这一点?下面的方法我如何通过进程id获取.exe文件路径。
public static string GetMainModuleFilepath(int processId)
{
string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
{
using (var results = searcher.Get())
{
ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
return (string)mo?["ExecutablePath"];
}
}
}
答案 0 :(得分:0)
我已经尝试了很多这些,下面是最适合我的示例代码。
无论它是32位还是64位应用程序,它都应该有效。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
namespace WmiTest
{
class Program
{
static void Main(string[] args)
{
int processID = 12624; // Change for the process you would like to use
Process process = Process.GetProcessById(processID);
string path = ProcessExecutablePath(process);
}
static private string ProcessExecutablePath(Process process)
{
try
{
return process.MainModule.FileName;
}
catch
{
string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject item in searcher.Get())
{
object id = item["ProcessID"];
object path = item["ExecutablePath"];
if (path != null && id.ToString() == process.Id.ToString())
{
return path.ToString();
}
}
}
return "";
}
}
}
请注意,您必须引用System.Management程序集并使用System.Management命名空间