推荐使用 AppDomain.CurrentDomain.BaseDirectory 获取发布后程序根目录;2. 开发时可用 Directory 向上追溯获取项目源码路径;3. 通过 Assembly.Location 获取程序集物理路径,但注意 .NET Core 中可能为空;4. ASP.NET Core 应通过 IWebHostEnvironment 获取 Web 根目录与内容根目录;5. 系统路径可借助 Environment 类获取,生产环境优先选用 BaseDirectory 或依赖注入避免硬编码。

在 .NET 中获取当前项目或文件的路径,要根据运行环境(如 .NET Framework 或 .NET Core/.NET 5+)以及具体需求来选择合适的方法。以下是几种常用方式:
方法:
string path = AppDomain.CurrentDomain.BaseDirectory;
示例:
string projectPath = Directory.GetParent(Directory.GetCurrentDirectory())?.Parent?.Parent?.FullName;
方法:
string assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; string directory = Path.GetDirectoryName(assemblyLocation);
示例:
public class MyService
{
private readonly string _webRootPath;
private readonly string _contentRootPath;
public MyService(IWebHostEnvironment env)
{
_webRootPath = env.WebRootPath; // wwwroot 路径
_contentRootPath = env.ContentRootPath; // 项目根目录(含 appsettings.json 等)
}
}Environment.CurrentDirectory:当前工作目录(可能受启动方式影响)Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments):获取“我的文档”等系统路径基本上就这些常见用法。开发时注意区分“编译输出路径”和“源码项目路径”,生产环境建议以 AppDomain.CurrentDomain.BaseDirectory 或依赖注入方式为主,避免硬编码路径逻辑。
以上就是.NET怎么获取当前项目或文件的路径的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号