Search code examples
c#.net-corememorystreamc#-7.0

How to read from a stream you've just written to without calling Flush() in C#


I have some code that uses a 3rd party library, EDIFabric, which writes to a stream, which I need to capture that output and use it to return a string by way of a StreamReader.

    // Build out the memory stream we'll use to conver to a string.
    using (var stream = new MemoryStream())
    {
        using (var writer = new X12Writer(stream))
        {
            writer.Write("Write EDI values to the stream"); // Not valid EDI output...

            writer.Flush();
            // Flush() is obsolete and generates a CS0618 compiler warning, "Type or member is obsolete"

            stream.Seek(0, SeekOrigin.Begin); // Return to the beginning of the stream
        }

        using StreamReader reader = new(stream);

        // If I omit the flush, the returned string is empty
        return reader.ReadToEnd(); // Returns the stream as a string
    }

Any suggestions that don't include using Flush()?


Solution

  • The solution for this problem was derived from @madreflection's comment above, simply moving the stream.Seek() out of the inner using block.

    // Build out the memory stream we'll use to conver to a string.
    using (var stream = new MemoryStream())
    {
        using (var writer = new X12Writer(stream))
        {
            writer.Write("Write EDI values to the stream"); // Not valid EDI output...
        }
        
        stream.Seek(0, SeekOrigin.Begin);
    
        using StreamReader reader = new(stream);
        return reader.ReadToEnd(); // Returns the stream as a string
    }