How to get the full path of running process?
I am having an application that is changing some settings of another application (it is a simple C# application that run by double clicking (no setup required)).
After changing the settings I need to restart the other application so that it reflects the changed settings.
So to do, I have to kill the running process and start the process again, But the problem is after killing I am not able to find the process. (Reason is system do not know where the exe file is..)
Is there any way to find out the path of running process or exe, if it is running?
I do not want to give path manually, i.e. if it is running get the path, kill the process and start again else .... I will handle later
using System.Diagnostics;
var process = Process.GetCurrentProcess(); // Or whatever method you are using
string fullPath = process.MainModule.FileName;
//fullPath has the path to exe.
There is one catch with this API, if you are running this code in 32 bit application, you'll not be able to access 64-bit application paths, so you'd have to compile and run you app as 64-bit application (Project Properties → Build → Platform Target → x64).
What you can do is use WMI to get the paths. This will allow you to get the path regardless it's a 32-bit or 64-bit application. Here's an example demonstrating how you can get it:
// include the namespace
using System.Management;
var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var query = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new
{
Process = p,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
};
foreach (var item in query)
{
// Do what you want with the Process, Path, and CommandLine
}
}
Note that you'll have to reference the System.Management.dll
assembly and use the System.Management
namespace.
For more info on what other information you can grab out of these processes such as the command line used to start the program (CommandLine
), see the Win32_Process class and WMI .NET for for more information.
I guess you already have the process object of the running process (e.g. by GetProcessesByName()). You can then get the executable file name by using
Process p;
string filename = p.MainModule.FileName;