Do I need to do StreamWriter.flush()?

前端 未结 2 727
说谎
说谎 2021-02-05 03:29

Suppose this C# code:

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


        
相关标签:
2条回答
  • 2021-02-05 03:56

    Update

    Nevermind this answer, I got confused with the writers...


    1. No, the order will be preserved (update: maybe not). Flush is useful/needed in other situations, though I can't remember when.
    2. I think so, using makes sure everything cleans up nicely.
    0 讨论(0)
  • 2021-02-05 04:15

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

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

    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();
    }
    

    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.

    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).

    0 讨论(0)
提交回复
热议问题