写入然后从一个MemoryStream阅读 [英] Writing to then reading from a MemoryStream
问题描述
我使用DataContractJsonSerializer,它喜欢输出流。我想顶部和尾部串行器的输出,所以我使用的StreamWriter到我所需要的额外的比特交替书写。
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();
}
}
当我这样做,我得到一个ArgumentException流是无法读取。
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.
推荐答案
三件事情:
- 请不要关闭
的StreamWriter
。这将关闭的MemoryStream
。你需要刷新,虽然作家。 - 阅读之前重置流的位置。
- 如果你要直接写入到流,你需要先刷新作家。
- Don't close the
StreamWriter
. That will close theMemoryStream
. You do need to flush the writer though. - Reset the position of the stream before reading.
- If you're going to write directly to the stream, you need to flush the writer first.
所以:
using (var stream = new MemoryStream())
{
var sw = new StreamWriter(stream);
sw.Write("{");
foreach (var kvp in keysAndValues)
{
sw.Write("'{0}':", kvp.Key);
sw.Flush();
ser.WriteObject(stream, kvp.Value);
}
sw.Write("}");
sw.Flush();
stream.Position = 0;
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
还有一个更简单的选择虽然。所有你与阅读的将其转换为字符串时流做。你可以做到这一点更简单:
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:
return Encoding.UTF8.GetString(stream.GetBuffer(), 0, stream.Length);
您可以做到这一点的之后的关闭流,因此,如果的StreamWriter
关闭它没关系。
You can do that after closing the stream, so it doesn't matter if the StreamWriter
closes it.
我被你直接写入流而言 - 是什么辑
?它是一个XML序列化,或者一个二进制?如果是二进制的,你的模型是有点瑕疵 - 你不应该不被非常小心它混合二进制和文本数据。如果是XML,你会发现,你在你的字符串的中间,这可能是有问题的结束与字节顺序标记。
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.
这篇关于写入然后从一个MemoryStream阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!