我需要做StreamWriter.flush()吗? [英] Do I need to do StreamWriter.flush()?

查看:181
本文介绍了我需要做StreamWriter.flush()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设此C#代码:

using (MemoryStream stream = new MemoryStream())
{
    StreamWriter normalWriter = new StreamWriter(stream);
    BinaryWriter binaryWriter = new BinaryWriter(stream);

    foreach(...)
    {
        binaryWriter.Write(number);
        normalWriter.WriteLine(name); //<~~ easier to reader afterward.
    }

    return MemoryStream.ToArray();
}

我的问题是:

  1. 我是否需要在内部使用冲洗 循环以保持秩序?
  2. 返回的MemoryStream.ToArray()是否合法?我使用using -block作为约定,恐怕会弄乱事情.
  1. Do I need to use flush inside the loop to preserve order?
  2. Is returning MemoryStream.ToArray() legal? I using the using-block as a convention, I'm afraid it will mess things up.

推荐答案

抓取先前的答案-我没有注意到您在同一流中使用了两个包装器.这对我来说有点冒险.

Scratch the previous answer - I hadn't noticed that you were using two wrappers around the same stream. That feels somewhat risky to me.

无论哪种方式,我都将StreamWriterBinaryWriter放在它们自己的using块中.

Either way, I'd put the StreamWriter and BinaryWriter in their own using blocks.

哦,是的,在MemoryStream上调用ToArray()是合法的-数据即使在处理后仍会保留.

Oh, and yes, it's legal to call ToArray() on the MemoryStream - the data is retained even after it's disposed.

如果您真的想使用两个包装器,我会这样做:

If you really want to use the two wrappers, I'd do it like this:

using (MemoryStream stream = new MemoryStream())
{
    using (StreamWriter normalWriter = new StreamWriter(stream))
    using (BinaryWriter binaryWriter = new BinaryWriter(stream))
    {
        foreach(...)
        {
            binaryWriter.Write(number);
            binaryWriter.Flush();
            normalWriter.WriteLine(name); //<~~ easier to read afterward.
            normalWriter.Flush();
        }
    }    
    return MemoryStream.ToArray();
}

我不得不说,尽管如此,我还是对在同一流中使用两个包装器有些警惕.在每次操作之后,您都必须保持刷新它们中的每一个,以确保最终不会出现奇数数据.您可以设置StreamWriter AutoFlush 属性设置为true可以缓解这种情况,我相信BinaryWriter当前实际上不 需要刷新(即,它不缓冲任何数据),但是依靠它会带来风险.

I have to say, I'm somewhat wary of using two wrappers around the same stream though. You'll have to keep flushing each of them after each operation to make sure you don't end up with odd data. You could set the StreamWriter's AutoFlush property to true to mitigate the situation, and I believe that BinaryWriter currently doesn't actually require flushing (i.e. it doesn't buffer any data) but relying on that feels risky.

如果必须混合二进制数据和文本数据,我将使用BinaryWriter并显式写入该字符串的字节,并使用Encoding.GetBytes(string)进行提取.

If you have to mix binary and text data, I'd use a BinaryWriter and explicitly write the bytes for the string, fetching it with Encoding.GetBytes(string).

这篇关于我需要做StreamWriter.flush()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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