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

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


当前回答

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

其他回答

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

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\

在VB.net

My.Application.Info.DirectoryPath

工作为我(应用类型:类库)。不太懂c#… 返回文件名为字符串的路径

我将此用于console + net 6

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)

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

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);