Here are few of the previous article to upload the file in wwwroot folder are as follows. Upload File in Asp.Net Core MVC Using C#.Net, Upload File Outside of wwwroot Asp.Net Core MVC 8 in C#.Net, Upload Image and Display Preview in Asp.Net Core 8 MVC Using C#.Net, How to Protect File for Direct Download in Asp.Net Core MVC, C#.Net, Search & Delete File from wwwroot in Asp.Net Core 8 MVC Using C#.Net, How to Create Text File in wwwroot in Asp.Net Core 8 MVC using C#.Net.
So, for this article first we will create a new asp.net core mvc application and in wwwrooot folder we will add a text file which we are going to download. This file we will download on button click.
[HttpGet]
public IActionResult Index()
{
return View();
} Now we will create a view and add the below code in it.@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Click To Download File</h1>
<a href="/Home/DownloadFile/" title="Download file"><b>DOWNLOAD</b></a>
</div>
In above code I have defined a href path. In this I have defined an action method name responsible for downloading the specified file. Now lets check the code.public IActionResult DownloadFile()
{
var memory = DownloadSinghFile("TestTextFile.txt", "wwwroot");
return File(memory.ToArray(), "text/plain", "TestTextFile.txt");
}
private MemoryStream DownloadSinghFile(string filename, string uploadPath)
{
var path = Path.Combine(Directory.GetCurrentDirectory(), uploadPath, filename);
var memory = new MemoryStream();
if (System.IO.File.Exists(path))
{
var data = System.IO.File.ReadAllBytes(path);
memory = new MemoryStream(data);
}
memory.Position = 0;
return memory;
}
Here we have created a method of name DownloadSinghFile of return type MemoryStream. Here we will read the file and return the memory stream of provided file. After that IActionResult will return the File type. Which make file to be downloaded. Here one thing to note. If you have a specific type of file you need the define the file type. Please check the list.{ ".txt", "text/plain"},
{ ".pdf", "application/pdf"},
{ ".doc", "application/vnd.ms-word"},
{ ".docx", "application/vnd.ms-word"},
{ ".xls", "application/vnd.ms-excel"},
{ ".xlsx", "application/vnd.ms-excel"},
{ ".png", "image/png"},
{ ".jpg", "image/jpeg"},
{ ".jpeg", "image/jpeg"},
{ ".gif", "image/gif"},
{ ".csv", "text/csv"},
{ ".zip", "application/zip"}
Now lets run the code to check the output.


