C#中BinaryWriter和MemoryStream的奇怪行为

时间:2013-07-10 00:33:49

标签: c# .net memorystream binarywriter

我有一个使用以下方法的课程:

public System.IO.Stream ToBinary ()
{
    int length = 4144;
    System.IO.Stream stream = null;
    System.IO.BinaryWriter writer = null;

    stream = new System.IO.MemoryStream(length);
    writer = new System.IO.BinaryWriter(stream);

    writer.Write(length);

    writer.Write(this._Width);
    writer.Write(this._Height);
    writer.Write(this._Stride);
    writer.Write(this._Bounds.X);
    writer.Write(this._Bounds.Y);
    writer.Write(this._Bounds.Width);
    writer.Write(this._Bounds.Height);

    writer.Write(this._A.Length);
    for (int i = 0; i < this._A.Length; i++) writer.Write(this._A [i]);
    writer.Write(this._R.Length);
    for (int i = 0; i < this._R.Length; i++) writer.Write(this._R [i]);
    writer.Write(this._G.Length);
    for (int i = 0; i < this._G.Length; i++) writer.Write(this._G [i]);
    writer.Write(this._B.Length);
    for (int i = 0; i < this._B.Length; i++) writer.Write(this._B [i]);

    writer.Flush();

    return (stream); // If I write the contents of stream to a byte array, each element is 0.
}

public static byte [] ToBytes (this System.IO.Stream stream)
{
    return (stream.ToBytes(0, (int) stream.Length));
}

public static byte [] ToBytes (this System.IO.Stream stream, int offset, int count)
{
    byte [] buffer = null;

    buffer = new byte [count];

    stream.Read(buffer, offset, count);

    return (buffer);
}

在上面的代码中,我知道写入流的至少一个值是非零的。转换为字节数组时生成的流包含全零。

我是否错误地使用了流和阅读器对象?

1 个答案:

答案 0 :(得分:3)

您的ToBytes方法从流的当前位置读取字节到流的末尾。如果流已经位于末尾,则它将读取零字节。 您的ToBinary方法返回的流定位在最后。

查看MemoryStream.ToArray Method

  

MemoryStream.ToArray方法

     

将流内容写入字节数组,而不管Position属性。