如何在控制台应用程序中找到应用程序的路径?

在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。


当前回答

对于控制台应用程序,您可以尝试这样做:

System.IO.Directory.GetCurrentDirectory();

输出(在我的本地机器上):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

或者你可以试试(最后有一个额外的反斜杠):

AppDomain.CurrentDomain.BaseDirectory

输出:

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

其他回答

你可以用这个代替。

System.Environment.CurrentDirectory

这里有一个可靠的解决方案,适用于32位和64位应用程序。

添加以下参考:

使用System.Diagnostics; 使用System.Management;

将此方法添加到项目中:

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<ManagementObject>() select mo["ExecutablePath"]).First().ToString();

                MethodResult = ExecutablePath;

            }

        }

    }
    catch //(Exception ex)
    {
        //ex.HandleException();
    }
    return MethodResult;
}

现在像这样使用它:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

注意,如果您知道进程的id,那么该方法将返回相应的ExecutePath。

有兴趣的同学可以额外订阅:

Process.GetProcesses() 

...将为您提供当前运行的所有进程的数组,并且…

Process.GetCurrentProcess()

...会给你当前的进程,以及他们的信息,如Id等,也有限制控制,如杀死等*

我没有看到任何人将. net Core反射提供的LocalPath转换为可用的系统。IO路径,这是我的版本。

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;
       
}

这将返回完整的C:\\xxx\\xxx格式的路径到您的代码所在的位置。

Path.GetDirectoryName (System.Diagnostics.Process.GetCurrentProcess () .MainModule.FileName) 是唯一一个在我尝试过的所有案例中都有效的方法。

如果你正在寻找一种与。net Core兼容的方法,请使用

System.AppContext.BaseDirectory

这是在。net Framework 4.6和。net Core 1.0(和。net Standard 1.3)中引入的。看到:AppContext。BaseDirectory财产。

根据这一页,

这是。net Core中AppDomain.CurrentDomain.BaseDirectory的首选替代品