Вопрос

I use the following snippet of code, and I'm unsure whether I need to call the Flush methods (once on StreamWriter, once on MemoryStream):

    //converts an xsd object to the corresponding xml string, using the UTF8 encoding
    public string Serialize(T t)
    {
        using (var memoryStream = new MemoryStream())
        {
            var encoding = new UTF8Encoding(false);

            using (var writer = new StreamWriter(memoryStream, encoding))
            {
                var serializer = new XmlSerializer(typeof (T));
                serializer.Serialize(writer, t);
                writer.Flush();
            }

            memoryStream.Flush();

            return encoding.GetString(memoryStream.ToArray());
        }
    }

First of all, because the code is inside the using block, I think the automatically called dispose method might do this for me. Is this true, or is flushing an entirely different concept?

According to stackoverflow itself:

Flush meaning clears all buffers for a stream and causes any buffered data to be written to the underlying device.

What does that mean in the context of the code above?

Secondly, the flush method of the MemoryStream does nothing according to the api, so what's up with that? why do we call a method that does nothing?

Это было полезно?

Решение

You don't need to use Flush on the StreamWriter, as you are disposing it (by having it in a using block). When it's disposed, it's automatically flushed and closed.

You don't need to use Flush on the MemoryStream, as it's not buffering anything that is written to any other source. There is simply nothing to flush anywhere.

The Flush method is only present in the MemoryStream object because it inherits from the Stream class. You can see in the source code for the MemoryStream class that the flush method actually does nothing.

Другие советы

In general Streams will buffer data as it's written (periodically flushing the buffer to the associated device if there is one) because writing to a device, usually a file, is expensive. A MemoryStream writes to RAM so the whole concept of buffering and flushing is redundant. The data is always in RAM already.

And yes, disposing the stream will cause it to be flushed.

Commenting flush method returning empty byte[], Though I am Using Using block

     byte[] filecontent = null;
        using var ms = new MemoryStream();
        using var sw = new StreamWriter(fs);
        sw.WriteCSVLine(new[] { "A", "B" });//This is extension to write as CSV
        //tx.Flush();
        //fs.Flush();
        fs.Position = 0;
        filecontent = fs.ToArray();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top