memorystream在读取时包含错误的xml标记

时间:2012-06-26 11:53:56

标签: c# xml stream httpwebresponse

我的问题是什么?当我将流写回web时,打开包含一些内容的文件,但所有内容都格式错误,有些内容丢失。

我是否因逻辑错误而导致数据丢失?

注意:下面的读取流和写入流模拟了服务将填写的内容。我将收到一个要从服务中读取的流。我需要将该流写出来。

        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 && readStream.Read(buffer, 0, buffer.Length) > 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();

1 个答案:

答案 0 :(得分:1)

  

我是否因逻辑错误而导致数据丢失?

是的,您可能会尝试简化您的代码。我不认为这里需要多个内存流:

OrderDocument doc = new OrderDocument();
doc.Format = "xml";
doc.DocumentId = "5555555";
doc.Aid = "ZZ";
doc.PrimaryServerPort = "PORT";
byte[] buffer = doc.GetDocument();

Response.Buffer = true;
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", doc.DocumentId));
Response.OutputStream.Write(buffer, 0, buffer.Length);