How to Create Text File in wwwroot in Asp.Net Core 8 MVC using C#.Net

How to create a text file in wwwroot folder as per user entered file name and data in asp.net core mvc using c#.net. data from view to controller .
In today's article I will show you how you create and write text on a text file in www.root folder in your asp.net core mvc application using c#.net.  Here I will demonstrate how you can create a text file as per user provided file name and data for the file. Here I have user TextBoxFor control for adding the File name and TextAreaFor control for adding the text file data in View on click on submit button.

Here I will also demonstrate how you can capture the user added value at the controller end with the help of model class property and create a text file as per user given file name in wwwroot folder and add or save the user provided value or data in the text file(.txt).

Now for this article first we will create a new asp.net core application. Here I have used .NET core 8. In this asp.net core mvc application we will create a folder in wwwroot, where we will create our text file. 

Empity folder in wwwroot folder

Now let's create a model class file and add the below code.

namespace Project.Models
{
    public class FileModel
    {
        public string TextFileName { get; set; }
        public string Filetextdetail { get; set; }
    }
}

In above model class file, I have declared two properties named as TextFileNameFiletextdetail. These properties I will use to capture the data and the file name from view to controller. Now let add a controller and add a IActionResult and annotate it with HttpGet. Here in this methos we will create object of model class file and pass it to view.

[HttpGet]
public IActionResult Index()
{
    FileModel fileModel = new FileModel();
    return View(fileModel);
}
Now let's create the view and add the below code in it.
@model FileModel
@{
    ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "Home"))
{
    <div style="color: red;">@ViewBag.Message</div>
    <div style="font-weight:bold;">Enter File Name</div>
    <div>
        @Html.TextBoxFor(m => m.TextFileName, new { @class = "form-control" })
    </div>
    <div style="font-weight:bold;">Enter Your Text</div>
    <div>
        @Html.TextAreaFor(m => m.Filetextdetail, new { @class = "form-control" })
    </div>
    <div><input type="submit" value="Add To Text File" /></div>
}
Here in above view code, I have added the reference of the model class file named as FileModel. Here one thing we need to check in asp.net core 8 mvc and above version for adding the model class reference we just need to user model class file name and with @model.

Please check the Form Tag, With HttpPost Action name and controller name. On other hand TextBoxFor to capture the file name and TextAreaFor to capture the file data. Now a Submit input button have been used so when user done by adding file name and file data, he will click on submit button, so that we can capture the details added in control in controller. Here ViewBag have been used for displaying the message to the user.
 [HttpPost]
 public IActionResult Index(FileModel fileModel)
 {
     string parentPath = @"\wwwroot\DemoFiles\";
     string finalPath = string.Format("{0}{1}{2}{3}",Directory.GetCurrentDirectory(), parentPath, fileModel.TextFileName , ".txt");
     if (!Path.Exists(finalPath))
     {
         //create file
         StreamWriter streamWriter = new StreamWriter(finalPath);
         //Write data to file
         streamWriter.WriteLine(fileModel.Filetextdetail);
         //Close the instance
         streamWriter.Close();
         ViewBag.Message = "File created successfully.....";
     }
     else
     {
         ViewBag.Message = "File already exists....";
     }
     return View(fileModel);
 }
The above code represents the HttpPost IActionResult method. Which will execute when user click on Submit button. Now here I have taken a variable to store the folder location where we want to create the text file. 
string finalPath = string.Format("{0}{1}{2}{3}",Directory.GetCurrentDirectory(), parentPath, fileModel.TextFileName , ".txt");
In above code I have used string.Format to concatenate the path string variables to get the path.  Here i have used Directory.GetCurrentDirectory() to get the directory path, parent folder path in wwwroot folder where we want to create the text file, model class property fileModel.TextFileName to get the user entered file name and in last i have passed the extension of the file as ".txt".

Now let's validate whether the file already exists or not. To validate the file, exist or not I have used Path.Exists(finalPath). If file does not exist I have used StreamWriter to generate the file and add the user entered value in the text file. 
         //create file
         StreamWriter streamWriter = new StreamWriter(finalPath);
         //Write data to file
         streamWriter.WriteLine(fileModel.Filetextdetail);
         //Close the instance
         streamWriter.Close();
         ViewBag.Message = "File created successfully.....";
After creating the file successfully. I have stored a message in ViewBag to display at the user end. Now we have done let's run the code by putting a break point.

Form in asp.net core mvc
Now click on button control our break point will hit. Here we can see the detail added by user we are getting in the model property.

Post action method in controller

Now press F5 to check the final output.

File created successfully in wwwroot folder in asp.net core mvc

Now let's check the wwwroot folder and for the created text file. 

Created text file wwwroot folder

File content.

Text file content in asp.net core mvc

Now let's check the if file already exists what will happen. Due to validation user will get a message that file already exists.

File already exists in wwwroot folder in asp.net core mvc
how-to-create-text-file-in-wwwroot-in-asp-net-core-8-mvc-using-c-net.zip 339KB

Post a Comment