How can I get the application's path in a .NET console application?

后端 未结 27 1414
甜味超标
甜味超标 2020-11-21 11:11

How do I find the application\'s path in a console application?

In Windows Forms, I can use Application.StartupPath to find the current path, but this d

27条回答
  •  孤独总比滥情好
    2020-11-21 11:57

    Here is a reliable solution that works with 32bit and 64bit applications.

    Add these references:

    using System.Diagnostics;

    using System.Management;

    Add this method to your project:

    public static string GetProcessPath(int processId)
    {
        string MethodResult = "";
        try
        {
            string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
    
            using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
            {
                using (ManagementObjectCollection moc = mos.Get())
                {
                    string ExecutablePath = (from mo in moc.Cast() select mo["ExecutablePath"]).First().ToString();
    
                    MethodResult = ExecutablePath;
    
                }
    
            }
    
        }
        catch //(Exception ex)
        {
            //ex.HandleException();
        }
        return MethodResult;
    }
    

    Now use it like so:

    int RootProcessId = Process.GetCurrentProcess().Id;
    
    GetProcessPath(RootProcessId);
    

    Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.

    Extra, for those interested:

    Process.GetProcesses() 
    

    ...will give you an array of all the currently running processes, and...

    Process.GetCurrentProcess()
    

    ...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*

提交回复
热议问题