0

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?

Raheel Khan
  • 14,205
  • 13
  • 80
  • 168
  • Are you using the `MemoryStream.ToArray` method to convert to an array? Are you calling this within a `Try...Catch` block and are there any exceptions thrown? – keyboardP Jul 10 '13 at 00:46
  • There is no try/catch and I am using extension methods to convert to byte arrays. Have included the method in the question above. – Raheel Khan Jul 10 '13 at 00:52

1 Answers1

3

Your ToBytes method reads the bytes from the current position of the stream to the end of the stream. 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.

Have a look at the MemoryStream.ToArray Method:

MemoryStream.ToArray Method

Writes the stream contents to a byte array, regardless of the Position property.

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
  • Thanks. Took care of the stream position everywhere except here. I am using the base Stream class since this method will be called from multiple places with MS as well as FileStream objects. – Raheel Khan Jul 10 '13 at 01:01
  • 1
    Note that `stream.Read(buffer, offset, count);` does not necessarily read `count` many bytes. It reads **up to** `count` many bytes. Have a look at http://stackoverflow.com/a/221941 – dtb Jul 10 '13 at 01:04