So, for this article first we will create a new asp.net core mvc application. In this we will add a controller. In this controller we will add a methos of return type IActionResult by decorating it with [HttpGet]. This will act as out page load.
[HttpGet]
public IActionResult Index()
{
return View();
}
In above code I have a return the View();. Now right click and add a view. In this view add the below code. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @Id = "form", @enctype = "multipart/form-data" }))
{
<h2>Create Folder</h2>
<br />
<div>
Enter folder name:
@Html.TextBox("foldername", "", new {@class="form-control"})<br />
<input type="submit" value="Create Folder" /><br />
<span style="color:red;font-weight:bold;">@ViewBag.Message</span>
</div>
}
In the code above I have defined the form tag. Under this form tag I have passed the action name and the controller name. This will help us to post the form when user clicks on the submit button. After defining the form tag, we take the TextBox and a submit input button. To display the end user message i have used ViewBag. Here to access the TextBox value in controller textbox control name will help. Now let's create a post method at controller end to create the folder as per entered folder name.
[HttpPost]
public IActionResult Index(string foldername)
{
string parentPath = @"\wwwroot\CustomFolder\";
string finalPath = string.Format("{0}{1}{2}",Directory.GetCurrentDirectory(), parentPath, foldername);
if (!Path.Exists(finalPath))
{
Directory.CreateDirectory(finalPath);
ViewBag.Message = "Folder created successfully.";
}
else
{
ViewBag.Message = "Folder already exists.";
}
return View();
}
In above code i have added parameter of string named as foldername. This parameter name same as the TextBox control name. This will help provide the user added value in textbox at controller end. After that i have created a parent folder where i will create the custom folder.In next line of code, I have defined the path where we are going to create the custom folder. Here we need to take case if we don't add Directory.GetCurrentDirectory() code will work correctly but folder will not create i in wwwroot folder in will create in root directory.
After preparing the path I have validated folder already exists or not, it does not exist next line of code will execute, and it will create the directory. Now let's run the code to check the output.
Here we are getting the user entered folder name. Now let's press F5 to check the final output.