我有一个Web API项目,从一些外部API调用中获取数据。 目前,我想将返回的数据以json的形式写入一个文件,并将该文件放置在我的项目中的一个文件夹中,以便可以为其他调用读取数据。 我必须将它们写入一个文件,而不是将信息存储在内存中。
我看过一些使用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,那是在你的汇编中。
你可以使用System.IO.File.WriteAllText来保存文件。
我建议你在你的项目路径中至少创建一个子文件夹。一般来说,没有理由将数据存储到你的项目的 "二进制文件夹"。在某个地方建立一个 "数据文件夹",并使用这个路径。