In my WPF project, I am receiving the path of the currently running process via the GetModuleFileNameEx method. It works in most cases, but for example when the currently running process is "Windows Explorer" (a system process), I get "C$Å" (and other random characters).
Delphi developers had a similar problem here and here. The first problem was solved by setting a debug privilege. Unfortunately, It seems, this doesn't help me in C#...
This is the method:
[DllImport("psapi.dll", SetLastError = true)]
private static extern int GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, StringBuilder lpFilename, int nSize);
// Get module file name
var buffer = new StringBuilder(4096);
GetModuleFileNameEx(hProcess, IntPtr.Zero, buffer, buffer.Capacity);
process = buffer.ToString();
You can use the
System.Diagnostics.Process class for that. Assuming you have the ID of a process you can use
var process = Process.GetProcessById(processId); var fileName = process.MainModule.FileName;