简体   繁体   中英

Error trying to download an XML file

I'm trying to download an XML file, the file already exists in the specified path, I am not familiar with VB and probably this code is not right , I need help just in it to be able to download an existing xml file, here's the code :

Protected Sub DownloadFile(ByVal sPath As String)
        Dim TargetFile As New System.IO.FileInfo(sPath)
        Response.Clear()
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
            TargetFile.Name)
        Response.AddHeader("Content-Length", TargetFile.Length.ToString())
        Response.ContentType = "text/xml"
        Response.WriteFile(TargetFile.FullName)
        Response.End()
End Sub

The error returned in the console:

Uncaught Error: Sys.WebForms.PageRequestManagerParserErrorException : The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

Contextualizing the problem :

I have serialized an object and created an XML file, then I would simply like to download this file, my difficulty is to download the file.

Dim oObj1 As New System.Xml.Serialization.XmlSerializer(GetType(eSocial.Eventos.evtTabHorTur.eSocial))
Dim sFileName = Date.Now.ToString("yyyyMMddHHmmss") & ".xml"
Dim sPath = Constantes.Ambiente.CaminhoSite & "temp\" & sFileName
Dim oFile As New System.IO.StreamWriter(sPath)
oObj1.Serialize(oFile, eSocialCamposXml)
oFile.Close()

You are saying you are having difficulty downloading but there is nothing in the code except showing writing a file and then serializing a file. You would be using a 'StreamReader' or similar manner to READ a file. Here is a simple example. Say I have an xml structure on a file location with the schema like:

<root>
    <test>Data</test>
</root>

I could write this in VB.NET to get it:

Sub Main()
  Dim xmlFile As XDocument
  Dim fileLocation = "D:\\Test Code\\Test.xml"
  Using sr = New StreamReader(fileLocation)
    xmlFile = XDocument.Parse(sr.ReadToEnd())
  End Using

  Console.WriteLine(xmlFile.Root.Element("test").Value.ToString)

  Console.ReadLine()
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM