I’m using DataContractJsonSerializer, which likes to output to a Stream. I want to top-and-tail the outputs of the serializer so I was using a StreamWriter to alternately write in the extra bits I needed.
var ser = new DataContractJsonSerializer(typeof (TValue));
using (var stream = new MemoryStream())
{
using (var sw = new StreamWriter(stream))
{
sw.Write("{");
foreach (var kvp in keysAndValues)
{
sw.Write("'{0}':", kvp.Key);
ser.WriteObject(stream, kvp.Value);
}
sw.Write("}");
}
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
When I do this I get an ArgumentException “Stream was not readable”.
I’m probably doing all sorts wrong here so all answers welcome. Thanks.
Three things:
StreamWriter. That will close theMemoryStream. You do need to flush the writer though.So:
There’s another simpler alternative though. All you’re doing with the stream when reading is converting it into a string. You can do that more simply:
Unfortunately
MemoryStream.Lengthwill throw if the stream has been closed, so you’d probably want to call theStreamWriterconstructor that doesn’t close the underlying stream, or just don’t close theStreamWriter.I’m concerned by you writing directly to the the stream – what is
ser? Is it an XML serializer, or a binary one? If it’s binary, your model is somewhat flawed – you shouldn’t mix binary and text data without being very careful about it. If it’s XML, you may find that you end up with byte-order marks in the middle of your string, which could be problematic.