[英]How to write a file to a project folder in .NET Core?
我有一个 Web API 项目,它从一些外部 API 调用中获取数据。 现在,我想将返回的数据作为 json 写入一个文件,并将该文件放在我项目的一个文件夹中,以便其他调用可以读取数据。 我必须将它们写入文件,而不是将信息存储在 memory 中。
我看过一些使用System.IO写文件的例子,但都是提到将文件写到项目外的本地文件系统中。
这样做的最佳方法是什么?
我正在使用 .NET Core 3.1。
我实际上找到了一个不使用反射的解决方案。 以下是我的代码:
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _env;
const string FileLocation = @"\Files\json.txt";
public GetTokenController(IConfiguration configuration, IWebHostEnvironment env)
{
_configuration = configuration;
_env = env;
}
public async Task<string>WriteFile(string jsonString)
{
string contentRootPath = _env.ContentRootPath;
var logPath = contentRootPath + FileLocation;
using (StreamWriter streamwriter = System.IO.File.CreateText(logPath))
{
await streamwriter.WriteLineAsync(jsonString);
}
return jsonString;
}
如果我理解得很好,你需要得到你的项目路径:
System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location
而不是 DaoTests 将任何 class 名称放入您的代码中,该名称位于您的程序集中。
比您可以使用 System.IO.File.WriteAllText 保存文件
我建议您在项目路径中至少创建一个子文件夹。 通常,没有理由将数据存储到项目的“二进制文件夹”中。 在某个地方创建“数据文件夹”并使用此路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.