memorystream contains bad xml markup when read <p>What is my issue here? When I write the stream back out to web, open the file it contains some of the content but all malformed and some missing.</p> <p>Am I experiencing loss of data due to a logic error?</p> <p><strong>Note:</strong> the readstream and writestream below mocks up what a service will be filling in. I will be receiving a stream to read from the service. I'll need to write that stream back out.</p> <pre><code> MemoryStream writeStream = new MemoryStream(); byte[] buffer = new byte[256]; OrderDocument doc = new OrderDocument(); doc.Format = "xml"; doc.DocumentId = "5555555"; doc.Aid = "ZZ"; doc.PrimaryServerPort = "PORT"; MemoryStream readStream = new MemoryStream(doc.GetDocument()); while (readStream != null &amp;&amp; readStream.Read(buffer, 0, buffer.Length) &gt; 0) { writeStream.Write(buffer, 0, buffer.Length); } writeStream.Flush(); writeStream.Position = 0; Response.Buffer = true; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "text/xml"; Response.ClearHeaders(); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", doc.DocumentId)); Response.AddHeader("Content-Length", writeStream.Length.ToString()); Response.BinaryWrite(writeStream.ToArray()); Response.End(); </code></pre>