C# 如何将文件写入.NET Core中的项目文件夹?

C# 如何将文件写入.NET Core中的项目文件夹?,c#,asp.net,asp.net-core,asp.net-core-webapi,C#,Asp.net,Asp.net Core,Asp.net Core Webapi,我有一个Web API项目,它从一些外部API调用获取数据。现在,我想将返回的数据作为json写入一个文件,并将该文件放在项目中的一个文件夹中,以便为其他调用读取数据。我必须将它们写入文件,而不是将信息存储在内存中 我见过一些使用System.IO编写文件的示例,但它们都提到将文件写入项目外部的本地文件系统 这样做的最佳方式是什么 我正在使用.NET Core 3.1。如果我理解得很好,您需要获得项目路径: 而不是将程序集中的任何类名放入代码中 然后可以使用System.IO.file.Wri

我有一个Web API项目,它从一些外部API调用获取数据。现在,我想将返回的数据作为json写入一个文件,并将该文件放在项目中的一个文件夹中,以便为其他调用读取数据。我必须将它们写入文件,而不是将信息存储在内存中

我见过一些使用System.IO编写文件的示例,但它们都提到将文件写入项目外部的本地文件系统

这样做的最佳方式是什么


我正在使用.NET Core 3.1。

如果我理解得很好,您需要获得项目路径:

而不是将程序集中的任何类名放入代码中

然后可以使用System.IO.file.WriteAllText保存文件


我建议您在项目路径中至少创建一个子文件夹。通常,没有理由将数据存储到项目的“二进制文件夹”中。在某处创建“数据文件夹”并使用此路径。

我实际上找到了一个不使用反射的解决方案。以下是我的代码:

        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;
        }
专用只读IConfiguration\u配置;
私人只读IWebHostEnvironment;
常量字符串FileLocation=@“\Files\json.txt”;
公共GetTokenController(IConfiguration配置,IWebHostEnvironment环境)
{
_配置=配置;
_env=env;
}
公共异步TaskWriteFile(字符串jsonString)
{
字符串contentRootPath=\u env.contentRootPath;
var logPath=contentRootPath+FileLocation;
使用(StreamWriter StreamWriter=System.IO.File.CreateText(logPath))
{
等待streamwriter.WriteLineAsync(jsonString);
}
返回jsonString;
}
        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;
        }