0

我有一个具有以下方法的类:

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

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

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

4

1 回答 1

3

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

看看MemoryStream.ToArray 方法

MemoryStream.ToArray 方法

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

于 2013-07-10T00:55:35.070 回答