0

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.

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

In the controller I do like below: // export to .xml here! ExportXMLModel e = new ExportXMLModel(); return e.DoExportXML(o.oTable); and the code doesn't function. No Save As dialog opens in Edge and Chrome, and I don't know where the file is saved….
… the DoExportXML does the same thing as Kenan's DownloadFile...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.