I'm trying to make a function which takes a Stream
(any type of stream, NetworkStream
,FileStream
, etc...) and write a byte array then reads the array, for this case I'm using BinaryWriter
and BinaryReader
.
The writing part works fine, I simply the BinaryWriter.Write
function.
but the reader part seems to raise an issue, especially when I use a NetworkStream
.
I couldn't find a way to read all the bytes from stream.
so I was wondering if it's even possible to read all bytes from a NetworkStream
while treating it as an object of type Stream
.
I could cast it to a socket then work with socket functions but I wonder if there's a way to write code that can work both with NetworkStream
and other type of streams.
these are the two functions:
Issue is inside first case, in the Deserialize
method
public static void Serialize(Stream stream, object obj)
{
BinaryWriter writer = new BinaryWriter(stream);
switch (Compression)
{
case FormatCompression.Binary:
writer.Write(BinaryDeconstructor.Deconstruct(obj));
break;
case FormatCompression.String:
writer.Write(Deconstructor.Deconstruct(obj));
break;
default:
throw new SerializationException("Please choose a format compression");
}
writer.Flush();
}
public static object Deserialize(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
switch (Compression)
{
case FormatCompression.Binary:
byte[] packet = /*HOW?!*/;
object obj = BinaryConstructor.Construct(packet);
return obj;
case FormatCompression.String:
//this case works fine
string objGraphData = reader.ReadString();
return Constructor.Construct(objGraphData);
default:
throw new SerializationException("Please choose a format compression");
}
}