tags:

views:

560

answers:

3

For a instance we have some IHttpHandler. where we have two valiables: XmlElement xmlResponse - contains a really big XML. HttpContext context - current HttpContext.

The simple solution:

context.Response.Write(xmlResponse.OwnerDocument.OuterXml);

but when a XML is really big we can get OutOfMemoryException at that line. A call stack will look like:

   at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
   at System.Text.StringBuilder.GetNewString(String currentString, Int32 requiredLength)
   at System.Text.StringBuilder.Append(Char value)
   at System.IO.StringWriter.Write(Char value)
   at System.Xml.XmlTextWriter.InternalWriteEndElement(Boolean longFormat)
   at System.Xml.XmlTextWriter.WriteFullEndElement()
   at System.Xml.XmlElement.WriteTo(XmlWriter w)
   at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
   at System.Xml.XmlElement.WriteTo(XmlWriter w)
   at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
   at System.Xml.XmlElement.WriteTo(XmlWriter w)
   at System.Xml.XmlDocument.WriteContentTo(XmlWriter xw)
   at System.Xml.XmlDocument.WriteTo(XmlWriter w)
   at System.Xml.XmlNode.get_OuterXml()

I'd write some such code:

HttpWriter writer = new HttpWriter(context.Response);
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
xmlResponse.OwnerDocument.WriteTo(xmlWriter);

But a problem is that HttpWriter's constructor is internal! HttpContext uses HttpWriter internally in Write methods.

What do workarrounds exist (except creating HttpWriter through reflection) ?

+1  A: 
xmlResponse.OwnerDocument.Save(Response.Output);
John Saunders
A: 

You can create a buffer by reading the file a few lines and then flushing things out, repeat and rinse. This can get you past the OutOfMemory exception, or should.

But if these are huge XML files, using HttpResponse and "writing" is not the best option. It is better to create and link and allow something other than the .NET Response object to deliver the files to the user. As such, I would seriously consider rethinking the architecture you are designing. Perhaps a file transfer web service might be better to transfer these large files? Just trying to post some ideas.

Am I missing something here?

Gregory A Beamer
+2  A: 

I would stream directly to the response.OutputStream

XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, 
System.Text.Encoding.UTF8);
Glennular
Small nit, but we should be using XmlWriter.Create(Response.Output) today. Creates the "right" kind of XmlWriter, and using the TextWriter uses the encoding already set.
John Saunders