如何获取运行中控制台应用程序的执行路径
How to Get a Running Process's Executable Path in C#
Great question! You’ve already got a solid start with your process-checking code. To grab the executable path of the target application, you can leverage the MainModule.FileName property from the Process class in System.Diagnostics. Let’s adjust your code to handle this—here are a couple of approaches depending on your needs:
Option 1: Get the Path of the First Matching Process
If you just need to confirm the process is running and get its path (or return null if it’s not), use this method:
using System.Diagnostics; using System; static public string GetProcessExecutablePath(string processName) { foreach (Process clsProcess in Process.GetProcesses()) { // ProcessName doesn't include the .exe extension, so match without it if (clsProcess.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)) { try { // MainModule.FileName gives the full executable path return clsProcess.MainModule.FileName; } catch (Exception ex) { // Some system/high-privilege processes block access—handle that here Console.WriteLine($"Could not access process {clsProcess.ProcessName}: {ex.Message}"); } } } return null; // Returns null if process isn't running or access is denied }
Option 2: Collect Paths for All Running Instances
If multiple instances of the same process might be running, use this to get all their paths:
using System.Collections.Generic; using System.Diagnostics; using System; static public List<string> GetAllProcessExecutablePaths(string processName) { List<string> executablePaths = new List<string>(); foreach (Process clsProcess in Process.GetProcesses()) { if (clsProcess.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)) { try { executablePaths.Add(clsProcess.MainModule.FileName); } catch (Exception ex) { Console.WriteLine($"Skipping process {clsProcess.Id}: {ex.Message}"); } } } return executablePaths; }
Key Notes:
- ProcessName vs. Executable Name: Remember that
Process.ProcessNamedoesn’t include the.exesuffix. So if you’re looking fornotepad.exe, pass"notepad"to the method. - Permission Handling: Some processes (like system services) require elevated privileges to access their module info. The try-catch blocks prevent your code from crashing when this happens.
- Usage Example:
string chromePath = GetProcessExecutablePath("chrome"); if (chromePath != null) { Console.WriteLine($"Chrome is running at: {chromePath}"); } else { Console.WriteLine("Chrome isn't running, or we don't have access to its path."); }
内容的提问来源于stack exchange,提问作者masiboo
相关产品推荐
相关产品推荐

