Writing to then reading from a MemoryStream

前端 未结 4 483
终归单人心
终归单人心 2020-11-28 09:09

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

4条回答
  •  庸人自扰
    2020-11-28 09:49

    setting the memory streams position to the beginning might help.

     stream.Position = 0; 
    

    But the core problem is that the StreamWriter is closing your memory stream when it is closed.

    Simply flushing that stream where you end the using block for it and only disposing of it fter you have read the data out of the memory stream will solve this for you.

    You may also want to consider using a StringWriter instead...

    using (var writer = new StringWriter())
    {
        using (var sw = new StreamWriter(stream))
        {
            sw.Write("{");
    
            foreach (var kvp in keysAndValues)
            {
                sw.Write("'{0}':", kvp.Key);
                ser.WriteObject(writer, kvp.Value);
            }
            sw.Write("}");
        }
    
        return writer.ToString();
    }
    

    This would require your serialization WriteObject call can accept a TextWriter instead of a Stream.

提交回复
热议问题