casaout casaout - 1 year ago 201
C# Question

GetModuleFileNameEx Function returns wrong path of system processes

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);

Here I call the method:

// Get module file name
var buffer = new StringBuilder(4096);
GetModuleFileNameEx(hProcess, IntPtr.Zero, buffer, buffer.Capacity);
process = buffer.ToString();

Did anyone face similar problems or has an idea how to solve this issue? Thanks.

Btw, I am running a Windows 8.1, 64bit machine.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download