最常用且跨平台可靠的方式是AppDomain.CurrentDomain.BaseDirectory,返回应用主程序集所在目录;单文件发布时需改用Path.GetDirectoryName(Environment.ProcessPath)获取原始路径。
在 Avalonia 中获取当前应用的运行路径,最常用且跨平台可靠的方式是通过 AppDomain.CurrentDomain.BaseDirectory 或 Assembly.GetExecutingAssembly().Location,但要注意两者含义不同——前者是应用主目录(即启动时的工作上下文),后者是当前程序集所在的物理路径。
这是最接近传统 WinForms/WPF 中 Application.StartupPath 的等价方案,适用于绝大多数场景(如读取同级配置文件、资源文件):
Directory.GetCurrentDirectory())影响,也不依赖调用栈
C#
string appPath = AppDomain.CurrentDomain.BaseDirectory;
若需精确获取 .dll 或 .exe 文件本身的位置(比如要读取同目录下的 JSON 配置),可用:
Assembly.GetEntryAssembly()?.Location —— 获取入口程序集(如 AvaloniaApp.dll 或 MyApp.exe)的完整文件路径Assembly.GetExecutingAssembly().Location —— 获取当前代码所在程序集路径(注意:若逻辑封装在独立类库中,可能不是主应用路径)GetEntryAssembly() 在某些宿主环境(如 dotnet watch)下可能返回 null安全写法示例:
C#string? exePath = Assembly.GetEntryAssembly()?.Location;
string appDir = exePath != null ? Path.GetDirectoryName(exePath) : AppDomain.CurrentDomain.BaseDirectory;
该方法返回的是进程的“当前工作目录”,它可被外部修改(如命令行启动时指定路径、IDE 运行配置里设置 Working Directory),**不可靠**,仅适合临时文件或用户显式指定路径的场景。
使用 dotnet publish -p:PublishSingleFile=true 发布时:
BaseDirectory 指向临时解压目录(如 /tmp/.net/MyApp/xxx/),不是原始发布路径Environment.ProcessPath(.NET 5+)获取启动进程路径,再用 Path.GetDirectoryName
Path.GetDirectoryName(Environment.ProcessPath)
基本上就这些。日常开发优先用 AppDomain.CurrentDomain.BaseDirectory,单文件部署时留意临时目录问题,按需切换到 Environment.ProcessPath。