0

I have a method to create an XML File and save it to the desired file path. It works perfectly. But the problem I am facing is I have to allow the user to download this file but it gets downloaded to the server on the given file path, not on the user's system.

I have the following code for the same

        var dateString1 = DateTime.Now.ToString("yyyyMMddHHmmss");

        XmlWriterSettings settings = new XmlWriterSettings
        {
            Indent = true,
            IndentChars = (" "),
            ConformanceLevel = ConformanceLevel.Fragment,
            CloseOutput = true,
            OmitXmlDeclaration = true
        };

        using (XmlWriter writer = XmlWriter.Create(filePath + "bill" + dateString1 + ".xml", settings))
        {                
            writer.WriteStartElement("HEADER");
            .......Some more Code..............
            writer.WriteEndElement(); //HEADER
            writer.Flush();
        }
        return Json(1, JsonRequestBehavior.AllowGet);

I need the file generated to be downloaded on the user's system automatically when he requests it and there is no other file generated.

Thank you.

  • 1
    If the network folder is shared you should be able to change filePath to the Network folder. – jdweng Dec 05 '19 at 13:27
  • try this https://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api – eyal Dec 05 '19 at 13:45

1 Answers1

3

In your controller:

var fileContent = System.IO.File.ReadAllBytes(filePath + "bill" + dateString1 + ".xml");
return File(fileContent , System.Net.Mime.MediaTypeNames.Text.Xml, "bill" + dateString1 + ".xml");

UPDATE. Without creating a file:

byte[] fileContent;
using (var ms = new MemoryStream())
{
    using (XmlWriter writer = XmlWriter.Create(ms, settings))
    {
        writer.WriteStartElement("HEADER");
        //.......Some more Code..............
        writer.Flush();
    }
    fileContent = ms.GetBuffer();
}

return File(fileContent , System.Net.Mime.MediaTypeNames.Text.Xml, "bill" + dateString1 + ".xml");