Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file with asp.net Core ? [duplicate]

Tags:

c#

.net-core

This is my first question on stackOverflow. After many research i don't find a way to download a file when the user go on the right URL.

With .Net Framework is used the following code :

        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", 
                       "attachment; filename=" + fileName + ";");
    response.TransmitFile(Server.MapPath("FileDownload.csv"));
    response.Flush();    
    response.End();

What is the equivalent with .Net core ? Thanks

like image 878
Boursomaster Avatar asked Dec 17 '22 19:12

Boursomaster


1 Answers

If you already have a controller, add an Action that return PhysicalFile for file on your disc or File for binary file in memeory:

[HttpGet]
public ActionResult Download(string fileName) {
    var path = @"c:\FileDownload.csv";
    return PhysicalFile(path, "text/plain", fileName);
}

To file path from project folder inject IHostingEnvironment and get WebRootPath (wwroot folder) or ContentRootPath (root project folder).

    var fileName = "FileDownload.csv";
    string contentRootPath = _hostingEnvironment.ContentRootPath;
    return PhysicalFile(Path.Combine(contentRootPath, fileName), "text/plain", fileName);
like image 83
Ivvan Avatar answered Jan 05 '23 01:01

Ivvan