1

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.

user1647160
  • 491
  • 1
  • 10
  • 25

2 Answers2

2

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;
        }
user1647160
  • 491
  • 1
  • 10
  • 25
0

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.