public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
Don't forget to use Using:
(不要忘记使用“使用”:)
using (var stream = GenerateStreamFromString("a,b
c,d"))
{
// ... Do stuff to stream
}
About the StreamWriter
not being disposed.
(关于StreamWriter
尚未处理。)
StreamWriter
is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. (StreamWriter
只是基本流的包装,并且不使用任何需要处理的资源。)
The Dispose
method will close the underlying Stream
that StreamWriter
is writing to. (Dispose
方法将关闭StreamWriter
写入的基础Stream
。)
In this case that is the MemoryStream
we want to return. (在这种情况下,我们要返回的是MemoryStream
。)
In .NET 4.5 there is now an overload for StreamWriter
that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.
(在.NET 4.5中, StreamWriter
现在有一个重载,可以在处置编写器后使基础流保持打开状态,但是此代码执行相同的操作,并且也可以与其他版本的.NET一起使用。)
See Is there any way to close a StreamWriter without closing its BaseStream?
(请参见是否可以在不关闭StreamWriter的BaseStream的情况下将其关闭?)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…