Reputation: 14787
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?
Upvotes: 0
Views: 1798
Reputation: 217303
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.
Upvotes: 3