karthik kasula
karthik kasula

Reputation: 37

How to Create a text File in Asp.net Core Application

I am new To Dot-net Core Application How to Create a text File in Asp.net Core Application Please provide Me some resource

Upvotes: 0

Views: 7436

Answers (2)

Fei Han
Fei Han

Reputation: 27825

How to Create a text File in Asp.net Core Application

If you'd like to create a text file at specific folder of your ASP.NET Core MVC project, you can refer to the following code snippet.

public class HomeController : Controller
{
    private IHostingEnvironment _env;

    public HomeController(IHostingEnvironment env)
    {
        _env = env;
    }

    public IActionResult Index()
    {
        var path = Path.Combine(_env.ContentRootPath, @"TxtFiles\" + "MyTest.txt");

        using (FileStream fs = System.IO.File.Create(path))
        {
            byte[] content = new UTF8Encoding(true).GetBytes("Hello World");

            fs.Write(content, 0, content.Length);
        }

        //code logic here
        //...

        return View();
    } 

Folder TxtFiles for saving text file(s)

enter image description here

Upvotes: 5

Stoyan Bukovich
Stoyan Bukovich

Reputation: 87

it's pretty much the same as the classic .NET

using System;
using System.IO;


        string path= Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        using (StreamWriter outputFile = new StreamWriter(Path.Combine(path, "myfile.txt")))
        {
                outputFile.WriteLine("Hello world!");
        }

Hope it helps.

Upvotes: 0

Related Questions