Download a file in C# from a .cshtml
To download a file in C# from a .cshtml file is a lot simpler than you think. All you need to download a file in C# mvc is a HttpPost method that can create bytes of your file. Then you use return File(), and there you go!
namespace MyProject.Controllers.DowloadFile
{
public class DownloadController : Controller
{
[HttpPost]
public ActionResult DownloadFile()
{
var fileBytes = System.IO.File.ReadAllBytes("FilePath.xlsx");
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "NameOfFileInDownload.xlsx");
}
}
}
@using (Html.BeginForm("DownloadFile", "Download", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h4>Download file:</h4>
<input type="submit" value="Start Download" class="submit" />
}
In the controller you can do other stuff as well of course, if you need to create the file you can do that. Another thing you can do is, extend the form to send in some data that you may need. Mabye you want to allow the user to name the file, then you can have an input field in the form and use that input to name the file in the end of the DownloadFile method.
In the link below is an article about how you can create an excel file in C# with a picture! Becuase if you want to download a file in C# from a .cshtml, you need a file to download!
Checkout these simple easy to read articles about add object to List, reverse for loops an foreach loops f you want som extra reading:
https://www.jennerstrand.se/add-object-to-list-in-c-sharp.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.
https://www.jennerstrand.se/foreach-loop-in-c-sharp-simple-use.
For loop in C# – Simple how to use and the links above is part of a series of easy read, quick use examples you can use in your c#/.net coding!