如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
当前回答
你可以用这个代替。
System.Environment.CurrentDirectory
其他回答
在VB.net
My.Application.Info.DirectoryPath
工作为我(应用类型:类库)。不太懂c#… 返回文件名为字符串的路径
在。net6中,我的WPF应用程序(<TargetFramework>net6.0-windows</TargetFramework>)返回Assembly.GetEntryAssembly()的.dll文件路径!位置,而不是。exe文件。他们引入了System.Environment.ProcessPath:
var path = Environment.ProcessPath; // Note it may be null
返回启动当前执行进程的可执行文件的路径。当路径不可用时返回null。
请参见这里和这里的讨论。
上面的答案是我需要的90%,但返回了一个Uri,而不是常规路径。
正如在MSDN论坛的帖子中解释的那样,如何将URI路径转换为正常的文件路径?,我使用了以下方法:
// Get normal filepath of this assembly's permanent directory
var path = new Uri(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
).LocalPath;
我没有看到任何人将. 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格式的路径到您的代码所在的位置。
我用过
System.AppDomain.CurrentDomain.BaseDirectory
当我想找到一个相对于应用程序文件夹的路径时。这适用于ASP。Net和winform应用程序。它也不需要任何对System的引用。Web组件。