views:

539

answers:

3

We have a VXML project that a 3rd party parses to provide us with a phone navigation system. We require them to enter an id code to leave a message, which is later reviewed by our company.

We currently have this working as follows:

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Stream m = new MemoryStream(); //Create Memory Stream - Used to create XML document in Memory
XmlTextWriter XML_Writer = new XmlTextWriter(m, System.Text.Encoding.UTF8);
XML_Writer.Formatting = Formatting.Indented;
XML_Writer.WriteStartDocument();
/* snip - writing a valid XML document */
XML_Writer.WriteEndDocument();
XML_Writer.Flush();
m.Position = 0;
byte[] b = new byte[m.Length];
m.Read(b, 0, (int)m.Length);
XML_Writer.Close();
HttpContext.Current.Response.Write(System.Text.Encoding.UTF8.GetString(b, 0, b.Length));

I'm just maintaining this app, I didn't write it...but the end section seems convoluted to me.

I know it's taking the output stream and feeding the written XML into it...but why is it first reading the entire string? Isn't that inefficient?

Is there a better way to write the above code?

+1  A: 

Yes, just write directly to the Response Output (IO.StreamWriter) or OutputStream (IO.Stream):

XmlTextWriter XML_Writer = new XmlTextWriter(HttpContext.Current.Response.OutputStream, HttpContext.Current.Response.Encoding);
//...
XML_Writer.Flush();
Duncan Smart
A: 

After that I can just call XML_Writer.Flush(), right? That'll flush the XML to the stream?

Jeff
Yes that should do it
Duncan Smart
A: 
Boaz
This only works with the XmlWriter class, not the XmlTextWriter I'm using...what would I lose by changing?
Jeff
The XmlTextWriter inherits from the XmlWriter Class. In principle the output vehicle (text/stream etc) is decoupled from the writing part. XmlWriter.Create was introduced in .NET 2.0 and is the "preferred way" of making XML writers. See the remarks section in the msdn doc of XmlWriter.Create.
Boaz