如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
当前回答
对于。net 6,有Environment.ProcessPath。
见https://learn.microsoft.com/en - us/dotnet/api/system.environment.processpath?view=net 6.0
其他回答
AppDomain.CurrentDomain.BaseDirectory
将解决问题,以引用第三方参考文件与安装包。
我已经使用了这段代码并得到了解决方案。
AppDomain.CurrentDomain.BaseDirectory
我将此用于console + net 6
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Path.GetDirectoryName (System.Diagnostics.Process.GetCurrentProcess () .MainModule.FileName) 是唯一一个在我尝试过的所有案例中都有效的方法。
我没有看到任何人将. 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格式的路径到您的代码所在的位置。