Search code examples
xmlasp.net-mvcdownloadupload

ASP.NET MVC: Dowloading data as a file to local computer. SAve As dialog


I generate a xml dynamically (serializing my custom type XMLDocType) in an ASP.NET MVC3 through the code below:

XMLDocType XMLdoc = new XMLDocType();
… generating contente for XMLdoc … 
XmlSerializer xml = new XmlSerializer(typeof(XMLDocType));

TextWriter writer = new StreamWriter("xmloutput.xml");

xml.Serialize(writer, XMLdoc);

writer.Close();

How can I dowload the xml content into the local computer (instead of server) through the normal downloading process in browsers (ie, opening a Save As dialog)?

Thank you.


Solution

  • you could use this class that extends ActionResult and return it in your MVC action. Also you write to MemoryStream instead of writing to local server file, and return it to user as response from Controller action.

    public class FileResult : ActionResult
    {
        public String ContentType { get; set; }
        public byte[] FileBytes { get; set; }
        public String SourceFilename { get; set; }
    
        public FileResult(byte[] sourceStream, String contentType, String sourceFilename)
        {
            FileBytes = sourceStream;
            SourceFilename = sourceFilename;
            ContentType = contentType;
        } 
    }
    
    public ActionResult DownloadFile()
    {   
        MemoryStream memoryStream = new MemoryStream(); 
        XMLDocType XMLdoc = new XMLDocType();
        XmlSerializer xml = new XmlSerializer(typeof(XMLDocType));
        TextWriter writer = new StreamWriter(memoryStream);
        xml.Serialize(writer, XMLdoc);
    
        FileResult file = new FileResult(memoryStream.ToArray(), "text/xml", "MyXMLFile.xml");
    
        writer.Close();
    
        return file;
    }