How to download xml file in asp.net using C#

后端 未结 2 905
再見小時候
再見小時候 2021-01-28 01:34

I am using an web application asp.net with mvc3. I am new to mvc3. I am having a download button on my webpage. when i am going to click the download button ,I

相关标签:
2条回答
  • 2021-01-28 02:14

    If you return FileResult it will be file, if you return string it will be open in browser.

    Update: This code will return file for downloading

    public FileResult GetXmlFile()
    {
        string xml=""; //string presented xml
        var stream = new MemoryStream();
        var writer = XmlWriter.Create(stream);
        writer.WriteRaw(xml);
        stream.Position = 0;
        var fileStreamResult = File(stream, "application/octet-stream", "xml.xml");
        return fileStreamResult;        
    }
    
    0 讨论(0)
  • 2021-01-28 02:21

    You can't pass a byte array, you need a Stream. Just pass a stream from your definition:

        public FileResult Download(string id) {
            string fid = Convert.ToString(id);
    
            var model = service.GetAllDefinitions().First(x => x.ID == id);
            var definitionDetails = new StatisticDefinitionModel(model);
            var definition = definitionDetails.ToXml;
    
            string fileName = definitionDetails.Name + ".xml";
            string contentType = "text/xml";
    
            return File(new MemoryStream(Encoding.Unicode.GetBytes(definition)), contentType, fileName);
        }
    
    0 讨论(0)
提交回复
热议问题