使用StreamWriter写入MemoryStream返回空 [英] Writing to MemoryStream with StreamWriter returns empty

查看:131
本文介绍了使用StreamWriter写入MemoryStream返回空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定自己在做什么错,已经看过很多例子,但是似乎无法解决这个问题.

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;
}

我正在对此方法做一个简单的测试,以尝试使其通过,但是无论如何,我的收藏计数为0.

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);
    }
}

注意:我在不编译Test方法的情况下更改了上面的某些语法.更重要的是第一个似乎返回空流的方法(我的reader.ReadLine()总是读取一次).不知道我在做什么错.谢谢.

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.

推荐答案

您忘记刷新StreamWriter实例.

public static Stream Foo()
{
    var memStream = new MemoryStream();
    var streamWriter = new StreamWriter(memStream);

    for (int i = 0; i < 6; i++)
        streamWriter.WriteLine("TEST");

    streamWriter.Flush();                                   <-- need this
    memStream.Seek(0, SeekOrigin.Begin);
    return memStream;
}

还要注意,由于StreamWriter实现了IDisposable,因此应该将其丢弃,但这又产生了另一个问题,它也会关闭底层的MemoryStream.

Also note that StreamWriter is supposed to be disposed of, since it implements IDisposable, but that in turn generates another problem, it will close the underlying MemoryStream as well.

确定要在此处返回MemoryStream吗?

我将代码更改为此:

public static byte[] Foo()
{
    using (var memStream = new MemoryStream())
    using (var streamWriter = new StreamWriter(memStream))
    {
        for (int i = 0; i < 6; i++)
            streamWriter.WriteLine("TEST");

        streamWriter.Flush();
        return memStream.ToArray();
    }
}

[Test]
public void TestStreamRowCount()
{
    var bytes = Foo();

    using (var stream = new MemoryStream(bytes))
    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);
    }
}

这篇关于使用StreamWriter写入MemoryStream返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆