Search code examples
c#.netserializationmemorystreamsystem.text.json

Why can't System.Text.Json serialize MemoryStream?


I have a class with a MemoryStream property. When I attempt to serialize it using System.Text.Json, I'm getting an exception:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Private.CoreLib.dll: 'Timeouts are not supported on this stream.'

using System.Text;
using System.Text.Json;

using var memoryStream = new MemoryStream();
var sampleText = "Hello, MemoryStream!";
var byteArray = Encoding.UTF8.GetBytes(sampleText);
memoryStream.Write(byteArray, 0, byteArray.Length);

var testClass = new TestClass
{
    Stream = memoryStream
};
var json = JsonSerializer.Serialize(testClass);

public class TestClass
{
    public MemoryStream Stream { get; set; }
}

How to fix this?


Solution

  • The reason you're getting this error is because the attempt to read either ReadTimeout or WriteTimeout (implemented in the base class System.IO.Stream) throws this exception (see here). The serializer attempts to read all the properties, and therefore fails.

    You need to provide a manual serialization, as Streams are not intended to be directly serialized. Stream inherits from MarshalByRefObject, a strong indication that the type is not intended for serialization, but should use by-reference semantics instead.