Here you can find a class I wrote that allows you to easily read and write byte arrays from and to a Stream. I created it because I needed such functionality on a NetworkStream (where you can't get the length of the stream).
using System;
using System.IO;
namespace TC.Utils {
public class StreamHelper {
private static byte[] ReadByteArray(Stream stream, int length) {
byte[] buffer = new byte[length];
int offset = 0;
while (offset < length)
offset += stream.Read(buffer, offset, length - offset);
return buffer;
}
private static void WriteInt32(Stream stream, int value) {
stream.Write(BitConverter.GetBytes(value), 0, 4);
}
private static int ReadInt32(Stream stream) {
return BitConverter.ToInt32(ReadByteArray(stream, 4), 0);
}
public static void WriteByteArray(Stream stream, byte[] data) {
WriteInt32(stream, data.Length);
if (data.Length > 0) stream.Write(data, 0, data.Length);
}
public static byte[] ReadByteArray(Stream stream) {
return ReadByteArray(stream, ReadInt32(stream));
}
}
}
To write:
Stream stream = ...;
byte[] data = ...;
StreamHelper.WriteByteArray(stream, data);
To read:
Stream stream = ...;
byte[] data = StreamHelper.ReadByteArray(stream);
EDIT 15 Oct 2005:
Martin Plante of
Xceed Software has given me some tips to make the code simpler (using
BitConverter instead of manually bit-shifting) and more robust. Thanks!
1 comments:
Watch out! Stream.Read may not always return the requested number of bytes. In ReadInt32, you ask of 4 bytes, but it may return 3, 2, or even a single byte. The only thing you can be sure is that it won't return 0 bytes unless it's at the end of the stream (or, in the case of a NetworkStream, it's disconnected).
Either use a BinaryReader around your stream, or loop until you read all bytes.
Also, instead of manually bit-shifting your "length", you can use System.BitConverter. It will simplify your code.
Post a Comment