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

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


当前回答

我没有看到任何人将. 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格式的路径到您的代码所在的位置。

其他回答

可能有点晚了,但这个值得提一下:

Environment.GetCommandLineArgs()[0];

或者更准确地获取目录路径:

System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

编辑:

相当多的人已经指出GetCommandLineArgs并不能保证返回程序名。请参见命令行上的第一个单词只是按照约定的程序名。这篇文章确实指出“尽管很少有Windows程序使用这个怪癖(我自己不知道)”。因此,“恶搞”GetCommandLineArgs是可能的,但我们谈论的是一个控制台应用程序。控制台应用程序通常是快速和肮脏的。所以这符合我的KISS哲学。

编辑 从反馈来看,当您使用单元测试系统时,大多数其他解决方案似乎都不起作用。这是有道理的,因为可执行项不是你的应用程序,而是测试系统。我还没有核实过,所以我可能完全错了。如果是这样,我将删除这一编辑。

你可能会这样做:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)

这里有一个可靠的解决方案,适用于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等,也有限制控制,如杀死等*

你可以用这个代替。

System.Environment.CurrentDirectory

对于。net 6,有Environment.ProcessPath。

见https://learn.microsoft.com/en - us/dotnet/api/system.environment.processpath?view=net 6.0