最常用且安全的方式是使用AppDomain.CurrentDomain.BaseDirectory获取exe所在目录;Environment.CurrentDirectory返回当前工作目录但可能变化;跨平台推荐AppContext.BaseDirectory或Assembly.GetExecutingAssembly().Location。
在C#中获取当前路径,关键要分清“当前工作目录”和“程序集所在目录”——这两者经常不同,选错会导致文件找不到。
这是最常用的需求,比如读取同级配置文件或资源。推荐用 AppDomain.CurrentDomain.BaseDirectory 或 Assembly.GetExecutingAssembly().Location 配合 Path.GetDirectoryName:
用 Environment.CurrentDirectory。注意:它可能被用户、调试器或第三方库修改,不一定等于exe位置。启动时默认是exe目录,但运行中可能变化。
直接用 Application.ExecutablePath(WinForms)或 Process.GetCurrentProcess().MainModule.FileName(通用):
.NET Core / .NET 5+ 推荐优先使用 AppContext.BaseDirectory(等价于 BaseDirectory)或 Assembly.GetExecutingAssembly().Location。避免硬编码 "..\\..\\" 这类相对路径,改用 Path.Combine 拼接:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json")
基本上就这些。多数情况下,AppDomain.CurrentDomain.BaseDi
rectory 是最安全、最直接的选择。