简体   繁体   English

C#中BinaryWriter和MemoryStream的奇怪行为

[英]Strange behavior with BinaryWriter and MemoryStream in C#

I have a class with the following method: 我有一个使用以下方法的类:

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

In the above code, I know that at least one of the values being written to the stream is non-zero. 在上面的代码中,我知道写入流的值中至少有一个是非零的。 The resulting stream when converted to a byte array, contains all zeros. 转换为字节数组时,结果流包含全零。

Am I using the stream and reader objects incorrectly? 我是否错误地使用了流和阅读器对象?

Your ToBytes method reads the bytes from the current position of the stream to the end of the stream. 您的ToBytes方法从流的当前位置到流的末尾读取字节。 If the stream is already positioned at the end, it reads zero bytes. 如果流已经位于末尾,则读取零字节。 The stream returned by your ToBinary method is positioned at the end. 您的ToBinary方法返回的流位于末尾。

Have a look at the MemoryStream.ToArray Method : 看看MemoryStream.ToArray方法

MemoryStream.ToArray Method MemoryStream.ToArray方法

Writes the stream contents to a byte array, regardless of the Position property. 不管Position属性如何,将流内容写入字节数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM