Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

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

You can write directly to the response stream:

Response.Cache.SetCacheability(HttpCacheability.NoCache);

XmlWriter XML_Writer = XmlWriter.Create(HttpContext.Current.Response.Output);

To add settings to the writer you are better off using the newer XmlWriterSettings class. Give it as a parameter to the XmlWriter.Create function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top