如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
当前回答
你可以简单地添加到你的项目引用System.Windows.Forms,然后像往常一样使用System.Windows.Forms. application . startuppath。
因此,不需要更复杂的方法或使用反射。
其他回答
你可能会这样做:
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
在。net Core 3及以上版本中,你会得到。dll文件而不是。exe文件。获取您可以使用的.exe文件路径。
var appExePath = Process.GetCurrentProcess().MainModule.FileName;
你可以用这个代替。
System.Environment.CurrentDirectory
下面一行将给出应用程序路径:
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
上述解决方案在以下情况下正常工作:
简单的应用 在另一个域,Assembly.GetEntryAssembly()将返回null DLL以字节数组的形式从嵌入式资源加载,并以Assembly.Load的形式加载到AppDomain。 使用Mono的mkbundle bundles(没有其他方法工作)
我用过
System.AppDomain.CurrentDomain.BaseDirectory
当我想找到一个相对于应用程序文件夹的路径时。这适用于ASP。Net和winform应用程序。它也不需要任何对System的引用。Web组件。