如何在控制台应用程序中找到应用程序的路径?
在 Windows Forms 中,我可以使用 Application.StartupPath
找到当前路径,但在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在 Windows Forms 中,我可以使用 Application.StartupPath
找到当前路径,但在控制台应用程序中似乎不可用。
AppDomain.CurrentDomain.BaseDirectory
以下代码将会给你应用程序的路径:
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
上述方案在以下情况下可以正常工作:
System.Windows.Forms
,然后像往常一样使用System.Windows.Forms.Application.StartupPath
。所以,不需要更复杂的方法或使用反射。System.AppDomain.CurrentDomain.BaseDirectory
当我想要查找相对于应用程序文件夹的路径时。这适用于ASP.Net和winform应用程序。它也不需要引用System.Web程序集。
我没有看到有人将 .Net Core 反射提供的 LocalPath 转换为可用的 System.IO 路径,因此这是我的版本。
public static string GetApplicationRoot()
{
var exePath = new Uri(System.Reflection.
Assembly.GetExecutingAssembly().CodeBase).LocalPath;
return new FileInfo(exePath).DirectoryName;
}
C:\\xxx\\xxx
,指向你的代码所在的位置。Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath
和 System.Reflection.Assembly.GetExecutingAssembly().CodeBase
有什么区别,您能详细说明一下吗? - RonC 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());
}
}
}
您可以像使用 Application.StartupPath 一样使用它:
Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
在VB.net中
My.Application.Info.DirectoryPath
对我来说可行(应用程序类型:类库)。不确定C#是否适用... 返回不带文件名的路径作为字符串
如果exe文件是通过双击来调用的,我会使用这个方法
var thisPath = System.IO.Directory.GetCurrentDirectory();
对于.NET 6,可以使用Environment.ProcessPath属性。
请查看https://learn.microsoft.com/en-us/dotnet/api/system.environment.processpath?view=net-6.0
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);