0

I work on project use .net core 2.2 visual studio 2017 Web API

I Need to make function download file

Give function path of file will be download and download file and return Void .

I need to make function do download file on .net core 2.2 to reuse it inside action controllers .

public void DownloadOutPut(string path)
{
    try
    {


        if (path != "")
        {


            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {

                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename = " + file.Name + "");
                Response.TransmitFile(path);


            }

            Response.End();
        }
    }
    catch (Exception ex)
    {

        throw;
    }
}

above done on asp.net web form I need to do function similar to it but on .net core 2.2

so How to do it please ?

ahmed barbary
  • 628
  • 6
  • 21

1 Answers1

1

I assume you are receiving a mapped path and the file is placed on your server.

public FileStreamResult DownloadFile(string path)
{
    var filename = System.IO.Path.GetFileName(path);
    var mimeType = "application/octet-stream";
    var stream = System.IO.File.OpenRead(path);

    return new FileStreamResult(stream, mimeType) { FileDownloadName = filename };
}

For mimetypes I found this SO answer helpful.

Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42