user7739271
user7739271

Reputation:

How to write to static file in asp.net core?

I'm making an example to write to static file (.txt).

I've tried:

    public IActionResult Index()
    {
        string dt = DateTimeOffset.Now.ToString("ddMMyyyy");

        string path = Path.Combine(_environment.WebRootPath, $"Logs/{dt}");

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        string filePath = Path.Combine(_environment.WebRootPath, $"Logs/{dt}/{dt}.txt");

        using (FileStream fs = System.IO.File.Create(filePath))
        {
            AddText(fs, "foo");
            AddText(fs, "bar\tbaz");
        }

        return View();
    }

    private void AddText(FileStream fs, string value)
    {
        byte[] info = new System.Text.UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }

But it created everything inside wwwroot folder instead of the root of project.

1

I want to create the text file here:

2

Where can I edit?

UPDATE:

This is how I define _environment:

public class HomeController : Controller
{
    private readonly IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
}

Upvotes: 2

Views: 4756

Answers (2)

DavidG
DavidG

Reputation: 118937

The problem is that you are using IHostingEnvironment.WebRootPath to determine the root folder. This property is the absolute path to the directory that contains the web-servable application content files - i.e. the wwwroot folder. Instead you should use the IHostingEnvironment.ContentRootPath property which will give you the absolute path to the directory that contains the application.

For example:

var contentRoot = _environment.ContentRootPath;
var webRoot = _environment.WebRootPath;

//contentRoot = "C:\Projects\YourWebApp"
//webRoot     = "C:\Projects\YourWebApp\wwwroot"

You could use WebRootPath and navigate to it's parent directory, but if for some reason you choose to move wwwroot somewhere else, your code may break. Much better to use a method that will give you the correct path every time in every project.

Upvotes: 5

John Wu
John Wu

Reputation: 52210

Instead of

string filePath = Path.Combine(_environment.WebRootPath, $"Logs/{dt}/{dt}.txt");

use

var folder = new System.IO.DirectoryInfo(_environment.WebRootpath).Parent.FullName;
var filePath = Path.Combine(folder, $"Logs/{dt}/{dt}.txt");

Upvotes: 0

Related Questions