推荐使用AppDomain.CurrentDomain.BaseDirectory获取执行程序目录;2. 通过Assembly.GetExecutingAssembly().Location获取编译后文件路径;3. ASP.NET Core中用IWebHostEnvironment.ContentRootPath和WebRootPath获取项目路径;4. 使用Path.Combine()安全拼接路径。
在 .NET 开发中,获取当前项目或文件的路径是一个常见需求,尤其是在读取配置文件、资源文件或日志写入时。不同场景下应使用不同的方法,避免硬编码路径,提高程序的可移植性。
如果需要获取当前运行的可执行文件(如
exe)所在的目录,可以使用 AppDomain.CurrentDomain.BaseDirectory 或 Environment.CurrentDirectory:
示例代码:
string basePath = AppDomain.CurrentDomain.BaseDirectory; // 推荐 string currentDir = Environment.CurrentDirectory;
在调试或开发过程中,有时需要获取某个源文件(如 .cs 文件)所在的目录。可通过 System.Reflection 获取程序集位置:
- Assembly.GetExecutingAssembly().Location: 获取当前执行程序集的路径(编译后的 dll/exe)。示例代码:
var assemblyLocation = Assembly.GetExecutingAssembly().Location; string directoryPath = Path.GetDirectoryName(assemblyLocation);
Web 项目中推荐通过依赖注入获取路径,而不是手动拼接:
- IWebHostEnvironment.ContentRootPath: 项目根目录,包含所有源文件。用法示例:
public class MyService
{
private readonly string _contentRoot;
public MyService(IWebHostEnvironment env)
{
_contentRoot = env.ContentRootPath;
}}
4. 处理相对路径与组合路径
避免直接拼接字符串路径,应使用 Path.Combine() 方法来确保跨平台兼容性:
string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "app.json");
这样可以在 Windows 和 Linux 系统中正确生成路径分隔符。
基本上就这些。根据项目类型选择合适的方法,控制好路径来源,就能稳定获取所需目录。