简体   繁体   中英

How to write a file to a project folder in .NET Core?

I have a Web API project that gets data from some external API calls. For now, I want to write the returned data as json to a file and place that file in a folder in my project so that the data can be read for other calls. I have to write them to a file and not store the information in memory.

I've seen some examples of using System.IO to write files, but they all reference writing the files to a local file system outside of the project.

What is the best way of doing this?

I'm using .NET Core 3.1.

I actually found a solution without using reflection. The following is my code:

        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;
        }

If I understand well, you need to get your project path:

How do I get the path of the assembly the code is in?

System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location

Instead of DaoTests put into your code any class name, that is in your assembly.

Than you can save the file using System.IO.File.WriteAllText

I suggest to you create at least a subfolder in your project path. Generally, there is no reason to store data to your "binary folder" of your project. Make somewhere you "data folder" and use this path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM