I get a list of processes

System.Diagnostics.Process[] procList = System.Diagnostics.Process.GetProcesses(); 

How to find out the folder where this process is located? Tried so

procList[0].MainModule.FileName - returns null

procList[0].StartInfo.FileName - returns an empty string

Are there any other ways?

  • I wrote the task manager for myself) The source code remained there and the path to the program and so on can help: NTaskManager - GooliveR
  • Do you want to get the path to the process file from where you start or all processes? - GooliveR
  • Try running like this: Console.WriteLine(Process.GetProcesses()[0].MainModule.FileName.ToString()); - GooliveR
  • one
    Use WMI as shown here - Stanislav Pechezerov
  • @ StanislavPezezerov yes, it fits, thank you very much - Lolidze

1 answer 1

If you need to get the program path from where you run your file:

 using System.Linq; using System.Diagnostics; try { foreach (var proc in Process.GetProcesses().Where(p => !string.IsNullOrEmpty(p.MainWindowTitle)).ToList()) { Console.WriteLine(proc.MainModule.FileName); } } catch { /*Тут ловим исключения*/ } 

Also without using Linq

 Console.WriteLine(Process.GetCurrentProcess().MainModule.FileName); 

The name of the file being run can be found out like this:

 Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)); 

To list all folders through processes, you can use this method:

 foreach (Process instance in Process.GetProcesses()) { try { Console.WriteLine(instance.ProcessName); Console.WriteLine(instance.MainModule.FileName); } catch (System.ComponentModel.Win32Exception w32ex) { Console.WriteLine(w32ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } } 

If you want to get all the process folders you can use via WMI

 using (var mCollection = new ManagementClass("Win32_Process").GetInstances()) { foreach (ManagementObject process in mCollection) { Console.WriteLine((string)process["ExecutablePath"]); //Console.WriteLine(FileVersionInfo.GetVersionInfo((string)process["ExecutablePath"]).FileDescription); } } 
  • If I correctly understood the example, then the code will not output all processes - Lolidze
  • @Lolidze, That's right) But if you need to output all the processes, use WMI - here’s an example: List Windows active processes in C # - GooliveR
  • one
    @Lolidze, Updated the answer - GooliveR