我在这里有什么问题? 当我将流写回 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();
我是否由于逻辑错误而遇到数据丢失?
是的,您可能尝试稍微简化一下代码。我真的没有看到这里需要多个内存流:
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);