How to download file from byte Array in asp.net core MVC?

Binumon George 21 Reputation points
2022-01-11T05:38:26.95+00:00

Hi All,
How to download XML data from byte array in Asp.net core. Below is my code

       string sXML = xml data in string format

        byte[] bytesInStream = System.Text.Encoding.UTF8.GetBytes(sXML);


        Please let me know whats the code for download in .net core MVC. The code working in .net framework MVC giving compile error. that code giving below

byte[] bytesInStream = System.Text.Encoding.UTF8.GetBytes(sXML);

        string fileName = FileName

        Response.Clear();
        Response.ContentType = "text/xml";
        Response.AddHeader("content-disposition", $"attachment; filename={fileName}");
        Response.BinaryWrite(bytesInStream);
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.End();
Developer technologies ASP.NET ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-01-11T12:32:18.837+00:00

    MVC controllers have a File return type.

    public IActionResult FileHandler(int id)
    {
        //look up the Id 
        var path = Path.Combine(Environment.ContentRootPath, @$"wwwroot/Content/{id}");
        var fileStream = System.IO.File.OpenRead(path);
        return File(fileStream, "application/pdf");
    }
    
    0 comments No comments

  2. Anonymous
    2022-01-12T08:40:39.493+00:00

    Hi @Binumon George ,

    I suggest you could return the file action which and add some response header inside this response to achieve your requirement. More details, you could refer to below codes:

            public IActionResult DownloadXML() {  
      
                string sXML = "<xml><test>1</test></xml>";  
      
                Byte[] bytesInStream = System.Text.Encoding.UTF8.GetBytes(sXML);  
      
      
                Response.Headers.Add("content-disposition", $"attachment; filename=test");  
      
                return File(bytesInStream, "application/xml");  
      
            }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.