问题描述
我的项目的文件夹结构如下:
My project has a folder structure to the tune of:
- 项目,
- 项目/数据
- 项目/引擎
- 项目/服务器
- 项目/前端
在服务器中(在 Project/Server 文件夹中运行)我指的是这样的文件夹:
In the server (running in the Project/Server folder) I refer to the folder like this:
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()
引用了当前文件夹,并且正在执行
On my windows machine this code works fine since Directory.GetCurrentDirectory()
reffered to the current folder, and doing
rootFolder.Substring(0, rootFolder.IndexOf(@"Project", StringComparison.Ordinal) + @"Project".Length);
让我获得项目的根文件夹(不是 bin 或 debug 文件夹).但是当我在 mac 上运行它时,它得到了Directory.GetCurrentDirectory()
"将我发送到/usr//[something else].它不是指我的项目所在的文件夹.
gets me the root folder of the project (not the bin or debug folders). But when I ran it on a mac it got "Directory.GetCurrentDirectory()
" sent me to /usr//[something else]. It didn't refer to the folder where my project lies.
在我的项目中查找相对路径的正确方法是什么?我应该在哪里存储数据文件夹,以便解决方案中的所有子项目都可以轻松访问它 - 特别是 kestrel 服务器项目?我更喜欢不必将其存储在 wwwroot 文件夹中,因为数据文件夹由团队中的其他成员维护,而我只想访问最新版本.我有哪些选择?
What is the correct way to find relative paths in my project? Where should I store the data folder in a way that it is easily accessible to all the sub projects in the solution - specifically to the kestrel server project? I prefer to not have to store it in the wwwroot folder because the data folder is maintained by a different member in the team, and I just want to access the latest version. What are my options?
推荐答案
取决于您在 kestrel 管道中的位置 - 如果您有权访问 IConfiguration
(Startup.cs
构造函数)或 IWebHostEnvironment
(以前的IHostingEnvironment
)你可以注入IWebHostEnvironment
进入您的构造函数或仅从配置中请求密钥.
Depending on where you are in the kestrel pipeline - if you have access to IConfiguration
(Startup.cs
constructor) or IWebHostEnvironment
(formerly IHostingEnvironment
) you can either inject the IWebHostEnvironment
into your constructor or just request the key from the configuration.
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
var contentRoot = env.ContentRootPath;
}
在 Startup.cs 构造函数中使用 IConfiguration
public Startup(IConfiguration configuration)
{
var contentRoot = configuration.GetValue<string>(WebHostDefaults.ContentRootKey);
}
这篇关于如何在asp.net core 中获取项目的根目录.Directory.GetCurrentDirectory() 在 Mac 上似乎无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!