1

In my ASP.NET MVC project, I have a text file called name.txt in a folder called data. I would like to write to it but I'm having a difficult time trying to reference it. My attempt:

string path = Path.Combine(Environment.CurrentDirectory, @"data/", name + ".txt");
StreamWriter file = new StreamWriter(path);
file.WriteLine("Write something in file");
file.Close();

Unfortunately, the error I receive is the path does not exist. Is there a simple and easy way to get the file path of the folders in an ASP.NET project?

Thanks

2
  • Request for clarification: one of the tags is asp.net-core, is this an ASP.NET MVC project (.NET Framework) or an ASP.NET Core MVC project (.NET Core)? Commented Mar 6, 2021 at 3:39
  • Hi, Adam! It's an ASP.NET Core MVC project Commented Mar 10, 2021 at 21:15

2 Answers 2

1

Couple things.

In ASP.NET Core, you'll want to retrieve the path that the app is running on from the IWebHostEnvironment interface. In the code below, you'll see in the constructor it's using Dependency Injection to get access to that.

It has two properties,

  • ContentRootPath is the root of the application
  • WebRootPath is the wwwroot folder

Also to simplify things I've refactored writing to the file with File.WriteAllText() which is a newer convenience wrapper around StreamWriter and does exactly what is shown in the answer.

Last thing that is personal preference I've opted for string interpolation $"" instead of concatenating with the +.

    public class FileSystemFileController : Controller
    {
        private readonly IWebHostEnvironment webHostEnvironment;

        public FileSystemFileController(IWebHostEnvironment webHostEnvironment)
        {
            this.webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index(string name)
        {
            string path = Path.Combine(webHostEnvironment.ContentRootPath, $"data/{name}.txt");
            System.IO.File.WriteAllText(path, "Write something on file");
            return View();
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I think you're looking for something like this,

string path = Path.Combine(Environment.CurrentDirectory, @"data/", name + ".txt");
using (StreamWriter file = new StreamWriter(path))
{
    file.Write("Write something on file");
}
file.Close();

Take note, using will fail on your second attempt, so you might want to look at the solution provided by @Danny Tuppeny on this question how to create .txt file and write it c# asp.net

Regards,

Joey

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.