Click to See Complete Forum and Search --> : How to find the path of external process?


gecka
February 18th, 2007, 02:05 PM
Hi to all! ;)

I want to get the directory a program was launched from. These processes aren't started in my code, they are started using the usual windows explorer.
I checked System.Diagnostics.Process and it doesn't seem it has that functionality.

Any help appreciated! :)

Zaccheus
February 18th, 2007, 06:06 PM
How would you identify the process you are looking for?

For example, if you know the process id, then you can create a Process object using System.Diagnostics.Process.GetProcessById. Or you can find all processes, using System.Diagnostics.Process.GetProcesses.

Each process object has a MainModule property from which you can get the full pathname.

StarShaper
February 18th, 2007, 09:41 PM
Use this:

using System.Runtime.InteropServices; // For P/Invoke

...

public class ModFilePath
{
[DllImport("kernel32.dll", SetLastError = true)]
[System.Security.SuppressUnmanagedCodeSecurity]

// DWORD GetModuleFileName(
// HMODULE hModule,
// LPTSTR lpFilename,
// DWORD nSize
// );
private static extern uint GetModuleFileName(
[In] IntPtr hModule,
[Out] StringBuilder lpFilename,
[In] [MarshalAs (UnmanagedType.U4)] int nSize);

public string StartupPath
{
get
{
StringBuilder sb = new StringBuilder(260);

if (GetModuleFileName(IntPtr.Zero, sb, sb.Capacity) == 0)
{
throw new ApplicationException("Could not retrive module file path!");
}

return Path.GetDirectoryName(sb.ToString());
}
}
}

Call with ModFilePath filepath = new ModFilePath(); and string localFileName = filepath.StartupPath

Zaccheus
February 19th, 2007, 04:10 AM
You don't need to use GetModuleFileName via p/invoke, you can get full pathname from the Process class' MainModule property.
;)

gecka
February 19th, 2007, 06:20 AM
Thank you for your help! ;)

About process identifying, I think there's no other way to do this, but use process' name. And that's why I needed path to the exe, to check if the program was launched from directory I need.

Zaccheus
February 19th, 2007, 06:41 AM
In that case, I think you can just call System.Diagnostics.Process.GetProcesses and itereate through the returned array.
:)