问题
Is there any reason why this code shouldn't produce a memory stream with the word Slappy in it?
private MemoryStream StringBuilderToMemoryStream(StringBuilder source)
{
MemoryStream memoryStream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(memoryStream);
streamWriter.Write("slappy");
return memoryStream;
}
Even if I say streamWriter.Write(source.toString());
it fails.
Funny thing is, that it works on one of the methods that calls this routine but not on any of the others.
And the order I call them in makes no difference either.
But regardless, even when I call the above, from the method that works, the output is still an empty MemoryStream.
Any thoughts?
回答1:
You don't flush the stream writer so the word never gets written to the memory stream.
Add the following after the call to streamWriter.Write
:
streamWriter.Flush();
Furthermore, if you want to read that word later from the memory stream, make sure to reset its position, because after the Write it is located after the word slappy
:
memoryStream.Position = 0;
回答2:
If you don't want to call streamWriter.Flush();
you can set the AutoFlush-Property of the StreamWriter, at the moment you create it.
MemoryStream memoryStream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(memoryStream)
{
AutoFlush = true
}
来源:https://stackoverflow.com/questions/16140109/cant-create-memorystream