如何确定是否正确填充了内存流

时间:2011-05-28 01:58:36

标签: c# .net memorystream streamwriter

下面的代码尝试用一些简单的文本填充message字节数组,直到缓冲区被填满。

byte[] message = new byte[1024];

using (MemoryStream memoryStream = new MemoryStream(message, true))
    {
        using (StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.ASCII))
        {
            while (???)
                streamWriter.WriteLine("Hello World!");
        }
    }

while(???)声明应该包含哪些内容?

1 个答案:

答案 0 :(得分:4)

byte[] message = new byte[1024];
using (MemoryStream memoryStream = new MemoryStream(message, true))
{
    using (StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.ASCII))
    {
        var lineToAdd = "Hello World!";
        while (memoryStream.Length - memoryStream.Position > lineToAdd.Length)
        {
            streamWriter.WriteLine(lineToAdd);
            streamWriter.Flush();
        }
    }
}

OR

using (MemoryStream memoryStream = new MemoryStream(message, true))
using (StreamWriter streamWriter = new StreamWriter(memoryStream, Encoding.ASCII))
{
    streamWriter.AutoFlush = true;
    var lineToAdd = "Hello World!";
    while (memoryStream.Length - memoryStream.Position > lineToAdd.Length)
        streamWriter.WriteLine(lineToAdd);
}