读取时数据从内存流中被截断 [英] Data is truncated from memory stream when reading

查看:95
本文介绍了读取时数据从内存流中被截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码正在使用 StreamWriter 写入 MemoryStream .但是,当我尝试读回流时,却截断了数据:

I have the following code that is using StreamWriter to write to a MemoryStream. However, when I try to read back the stream I am getting truncated data:

using(var outStream = new MemoryStream())
using (var outWriter = new StreamWriter(outStream))
{
    // my operation that's writing data to the stream

    var outReader = new StreamReader(outStream);
    outStream.Flush();
    outStream.Position = 0;
    return outReader.ReadToEnd();

}

这将返回大多数数据,但会在结尾处截断.但是,我知道数据正在流中,因为如果我尝试写入文件而不是 MemoryStream ,则会得到全部内容.例如,此代码将全部内容写入文件:

This returns most of the data, but truncates near the end. However, I know the data is getting to the stream because if I try to write to a file instead of a MemoryStream I get the entire contents. For example, this code writes the entire contents to file:

using (var outWriter = new StreamWriter(@"C:\temp\test.out"))
{
    // my operation that's writing data to the stream
}

推荐答案

您不是要刷新编写器-刷新 outStream 是没有意义的,因为没有什么可以刷新它的.您应该具有:

You're not flushing the writer - flushing outStream is pointless, as there's nothing to flush it to. You should have:

outWriter.Flush();

在倒带之前.您后面的代码证明数据到达了 writer 而不是 stream .

before you rewind. Your later code proves that the data reaches the writer - not the stream.

或者,从一开始就使用 StringWriter ...这是创建 TextWriter 并随后将文本写入其中的更简单的方法.

Alternatively, just use StringWriter from the start... that's a much simpler way of creating a TextWriter and then getting the text written to it later on.

这篇关于读取时数据从内存流中被截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆