使用 StreamWriter 写入 MemoryStream 返回空
我不确定我做错了什么,看过很多例子,但似乎无法让它发挥作用。
public static Stream Foo()
{
var memStream = new MemoryStream();
var streamWriter = new StreamWriter(memStream);
for (int i = 0; i < 6; i++)
streamWriter.WriteLine("TEST");
memStream.Seek(0, SeekOrigin.Begin);
return memStream;
}
我正在对此方法进行简单的测试,试图让它通过,但无论如何,我的集合计数都是 0。
[Test]
public void TestStreamRowCount()
{
var stream = Foo();
using (var reader = new StreamReader(stream))
{
var collection = new List<string>();
string input;
while ((input = reader.ReadLine()) != null)
collection.Add(input);
Assert.AreEqual(6, collection.Count);
}
}
注意:我更改了上面的一些语法,而没有在测试方法中进行编译。更重要的是第一个方法似乎返回一个空流(我的 reader.ReadLine() 总是读取一次)。不确定我做错了什么。谢谢。
I am not sure what I am doing wrong, have seen a lot of examples, but can't seem to get this working.
public static Stream Foo()
{
var memStream = new MemoryStream();
var streamWriter = new StreamWriter(memStream);
for (int i = 0; i < 6; i++)
streamWriter.WriteLine("TEST");
memStream.Seek(0, SeekOrigin.Begin);
return memStream;
}
I am doing a simple test on this method to try and get it to pass, but no matter what, my collection count is 0.
[Test]
public void TestStreamRowCount()
{
var stream = Foo();
using (var reader = new StreamReader(stream))
{
var collection = new List<string>();
string input;
while ((input = reader.ReadLine()) != null)
collection.Add(input);
Assert.AreEqual(6, collection.Count);
}
}
Note: I changed some syntax above without compiling in the Test method. What is more important is the first method which seems to be returning an empty stream (my reader.ReadLine() always reads once). Not sure what I am doing wrong. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您忘记刷新您的 StreamWriter 实例。
另请注意,
StreamWriter
应该被释放,因为它实现了IDisposable
,但这又会产生另一个问题,它将关闭底层的MemoryStream
> 也是如此。您确定要在此处返回
MemoryStream
吗?我会将代码更改为:
You are forgetting to flush your
StreamWriter
instance.Also note that
StreamWriter
is supposed to be disposed of, since it implementsIDisposable
, but that in turn generates another problem, it will close the underlyingMemoryStream
as well.Are you sure you want to return a
MemoryStream
here?I would change the code to this:
由于您没有使用“using”或streamWriter.Flush(),编写器没有向流提交更改。结果 Stream 本身还没有数据。一般来说,您希望使用 using 包装对 Stream 和 StremaWriter 实例的操作。
您还应该考虑返回 MemoryStream 的新实例:
Since you are not using "using" or streamWriter.Flush() the writer did not commit changes to the stream. As result Stream itslef does not have data yet. In general you want to wrap manipulation with Stream and StremaWriter instances with using.
You also should consider returning new instance of MemoryStream:
写完你的行后尝试刷新streamWriter。
Try flushing streamWriter after writing your lines.