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

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


当前回答

AppDomain.CurrentDomain.BaseDirectory

将解决问题,以引用第三方参考文件与安装包。

其他回答

Assembly.GetEntryAssembly()。Location或Assembly.GetExecutingAssembly().Location

与System.IO.Path.GetDirectoryName()结合使用只获取目录。

来自GetEntryAssembly()和GetExecutingAssembly()的路径可以不同,即使在大多数情况下目录是相同的。

使用GetEntryAssembly(),你必须意识到,如果入口模块是非托管的(即c++或VB6可执行文件),它可能返回null。在这些情况下,可以使用Win32 API中的GetModuleFileName:

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);

为什么不是p/invoke方法呢?

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    public class AppInfo
    {
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
            private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
            private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
            public static string StartupPath
            {
                get
                {
                    StringBuilder stringBuilder = new StringBuilder(260);
                    GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
                    return Path.GetDirectoryName(stringBuilder.ToString());
                }
            }
    }

您可以像使用应用程序一样使用它。StartupPath:

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

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

您可以使用下面的代码来获取当前应用程序目录。

AppDomain.CurrentDomain.BaseDirectory

试试下面这行简单的代码:

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);