如何在asp.net核心中获取项目的根目录。 Directory.GetCurrentDirectory()似乎无法在mac上正常工作

我的项目有一个文件夹结构:

  • 项目,
  • 项目/数据
  • 项目/发动机
  • 项目/服务器
  • 项目/前端

在服务器中我引用这样的文件夹:

var rootFolder = Directory.GetCurrentDirectory(); rootFolder = rootFolder.Substring(0, rootFolder.IndexOf(@"\Project\", StringComparison.Ordinal) + @"\Project\".Length); PathToData = Path.GetFullPath(Path.Combine(rootFolder, "Data")); var Parser = Parser(); var d = new FileStream(Path.Combine(PathToData, $"{dataFileName}.txt"), FileMode.Open); var fs = new StreamReader(d, Encoding.UTF8); 

在我的Windows机器上,这个代码工作正常,因为Directory.GetCurrentDirectory()引用了当前文件夹,并且正在执行

 rootFolder.Substring(0, rootFolder.IndexOf(@"\Project\", StringComparison.Ordinal) + @"\Project\".Length); 

获取项目的根文件夹(不是bin或debug文件夹)。 但是当我在Mac上运行它时,“ Directory.GetCurrentDirectory() ”将我发送到/ usr // [其他]。 它没有引用我的项目所在的文件夹。

在我的项目中找到相对路径的正确方法是什么? 我应该在哪里存储数据文件夹,以便解决方案中的所有子项目都可以轻松访问 – 特别是对于kestrel服务器项目? 我不想将它存储在wwwroot文件夹中,因为数据文件夹由团队中的其他成员维护,我只想访问最新版本。 我有什么选择?

如前所述(并收回)。 要获取基本目录(如在运行程序集的位置),请不要使用Directory.GetCurrentDirectory(),而是从IHostingEnvironment.ContentRootPath获取它。

 private IHostingEnvironment _hostingEnvironment; private string projectRootFolder; public Program(IHostingEnvironment env) { _hostingEnvironment = env; projectRootFolder = env.ContentRootPath.Substring(0, env.ContentRootPath.LastIndexOf(@"\ProjectRoot\", StringComparison.Ordinal) + @"\ProjectRoot\".Length); } 

但是我又犯了一个错误:我在启动时将ContentRoot目录设置为Directory.GetCurrentDirectory(),从而破坏了我所希望的默认值! 在这里,我评论了违规行:

  public static void Main(string[] args) { var host = new WebHostBuilder().UseKestrel() // .UseContentRoot(Directory.GetCurrentDirectory()) //<== The mistake .UseIISIntegration() .UseStartup() .Build(); host.Run(); } 

现在它运行正常 – 我现在可以导航到我的项目root的子文件夹:

 var pathToData = Path.GetFullPath(Path.Combine(projectRootFolder, "data")); 

我通过阅读BaseDirectory与当前目录以及@CodeNotFound创建的答案(由于上述错误导致其无效)而意识到我的错误,基本上可以在这里找到: 在Asp.net中获取WebRoot路径和内容根路径核心

根据您在Kestrel管道中的位置 – 如果您可以访问IConfigurationStartup.cs构造函数 )或IHostingEnvironment您可以将IHostingEnvironment注入构造函数或只是从配置中请求密钥。

Startup.cs构造函数中注入IHostingEnvironment

 public Startup(IConfiguration configuration, IHostingEnvironment env) { var contentRoot = env.ContentRootPath; } 

在Startup.cs构造函数中使用IConfiguration

 public Startup(IConfiguration configuration) { var contentRoot = configuration.GetValue(WebHostDefaults.ContentRootKey); } 

在某些情况下, _hostingEnvironment.ContentRootPathSystem.IO.Directory.GetCurrentDirectory()目标指向源目录。 这是关于它的错误 。

那里提出的解决方案帮助了我

 Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); 

试试这里: 获取应用程序文件夹路径的最佳方法

从那里引用:

System.IO.Directory.GetCurrentDirectory()返回当前目录,该目录可能是也可能不是应用程序所在的文件夹。 Environment.CurrentDirectory也是如此。 如果您在DLL文件中使用它,它将返回进程运行的路径(在ASP.NET中尤其如此)。