Search code examples
c#streamjson.netstreamwriterjsonserializer

How to prevent Newtonsoft JsonSerializer to close the stream?


So I haven't written the code I'm dealing right now and I'm looking how to best handle this.

Right now I have this.

public static void WriteSymbol(Stream stream, Symbol symbol)
{
    using (var streamWriter = new StreamWriter(stream))
    {
        JsonSerializer.Create(SerializerSettings).Serialize(streamWriter, symbol);                
    }
}

I'd like to be able to read the content of the stream after this is done in my test so that I can check the integration. The problem is that right now after Serialize the stream is closed and I can't read anymore from it.

I see that JsonWriter public bool CloseOutput { get; set; } but I don't see something for this static JsonSerializer.

What would be the best way to go about this? How do I prevent the Serializer from closing the stream? Is there some way I should check the content of the Stream?


Solution

  • From .net 4.5 upwards you can use the LeaveOpen constructor argument of StreamWriter.

    The default buffer size used by the StreamWriter is 1024 as visible when decompiling the type.

    So you can do the following.

    using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, 1024, true))
    {
        // TODO: do something 
    }