Rename Uploaded File in Asp.Net Core MVC Using C#.Net

How to rename the uploaded file in wwwroot folder in asp.net core 8 mvc application using c#.net. IFormFile to get the uploaded file in controller.
In todays article I will show you a simple tutorial with an example to how to renames the uploaded file in and save in wwwroot folder in asp.net core 8 mvc using c#.net. Validate file is selected or not in controller. Now for this article first we will create a new asp.net core 8 mvc application using c#.net. In this application add or create folder in wwwroot folder.

Folder in wwwroot Folder

Now lets add a controller file. In this controller file we will add a IActionResult method of HttpGet Type. Please check the below code.

 [HttpGet]
public IActionResult Index()
{
    return View();
} 
In above code a method of HttpGet type named as Index of return type IActionResult. Now we will the create a view and add the below code in it.
 @{
    ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    <div style="color:red" id="divmessage">@ViewBag.Message</div>
    <div style="font-weight:bold;">Select File:</div>
    <div>
        <input type="file" class="form-control" name="file" id="filecontrol" />
    </div>
    <br />
    <div>
        <input type="submit" value="Upload File"/>
    </div>
} 
Here in above code please refer the Form tag.
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
Here Html.BeginForm methos is used for defining the form tag. In this method we need to add the Action name and the controller name and Form Method Type as Post. This piece of code will define that when user click on submit button which method need to execute at controller end.  Here one of the most important thing which we need to take care new { @enctype = "multipart/form-data" }. If we don't add this html attribute, we will not be able to get the selected file at the controller end. 

In next line I have taken the div control to display the message. Here I have taken the @ViewBag.Message to display the message send from controller end. In next line I have taken the input control of file type. to upload the browse the file. Here I have taken the file control name as name='file'. This name of the file must be same as the parameter passed to the HttpPost  method. In last we have used Input button of submit type this will help us to post the form detail. Now lets create the HttpPost method. Refer the below code. 
[HttpPost]
public IActionResult Index(IFormFile file)
{
    if (file != null)
    {
        try
        {
            string parentPath = @"wwwroot\Demofiles\";
            Guid guid = new Guid();
            //New file name
            string new_FileName = string.Format("{0}{1}{2}", guid.ToString() , "." , Path.GetExtension(file.FileName));
            string uploadfilepath = Path.Combine(Directory.GetCurrentDirectory(), parentPath, new_FileName);
            var filestream = new FileStream(uploadfilepath, FileMode.Create);
            file.CopyToAsync(filestream);
            string dbSaveUploadPath = string.Format("{0}{1}", @"\Demofiles\", new_FileName);
            ViewBag.Message = "File uploaded successfully. With name "+ new_FileName;
        }
        catch (Exception ex)
        {
            ViewBag.Message = ex.Message;
        }
    }
    else
    {
        ViewBag.Message = "Please select file to upload.";
    }
    return View();
} 
In above code I have written the code for HttpPost method named as Index of return type IActionResult. In this method i have used try catch block to handle exception. In next line I have take a variable where we want to save the file. 

In next line I have taken the GUID which we will the name of the file which we will replace the name of the file. To get the extension of the uploaded file name by using Path.GetExtension(file.FileName). To prepare the file name I have used string.Format to combine the string file name. 
string new_FileName = string.Format("{0}{1}", guid.ToString() + "." + Path.GetExtension(file.FileName));
Now to prepare the upload file path Path.Combine. Now prepare the file stream and by using CopyToAsync to make the copy of the uploaded file in the folder. Now we have done lets run the code to check the output.

Upload File in Asp.Net Core

Now select the file and click on upload button.

Select Upload File in Asp.Net Core

Now click on Upload file button.

GUID In C#

Here in above code we are getting the Guid and this we will use as new file name.

New File name

Here in above code we are having the file name.

File Uploaded Successfully

Now lets check the wwwroot folder for the uploaded file in your asp.net core mvc appciation.

wwwroot Folder

Post a Comment