Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing arbitrary type instances into a MemoryStream in C#

In Delphi, one can do the following:

var
  ms  : TMemoryStream;
  i   : Integer;
begin
  ms := TMemoryStream.Create;
  i := 1024;
  ms.Write(@i, SizeOf(Integer));
  ms.Free;
end;

This will write the memory contents of i into ms.

The .Net version of MemoryStream doesn't have such a feature (neither the managed nor unmanaged versions). I know .Net doesn't work on the same principles as Delphi in this regard.

How does one do this in C#? I am interested in the "best practice" and the fastest methods.

like image 763
IamIC Avatar asked Mar 12 '12 07:03

IamIC


2 Answers

You can Serialize your object to a byte array

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);
    return ms.ToArray();
}

// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);
    return obj;
}

And then use MemoryStream to write it as wanted

byte[] mData = ObjectToByteArray(myObject);
MemoryStream memStream = new MemoryStream();
memStream.write(mData, 0, mData.Length);

EDIT: If you want to write an integer, use

byte[] mData = BitConverter.GetBytes((UInt16)iInteger);
memStream.write(mData, 0, mData.Length);
like image 154
Shai Avatar answered Oct 13 '22 22:10

Shai


Try using BinaryWriter on top of MemoryStream:

MemoryStream memoryStream = new MemoryStream(); 
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((int)123);

Note: don't forget to Dispose streams and writers/readers in real code, i.e. by using .

like image 25
Alexei Levenkov Avatar answered Oct 13 '22 23:10

Alexei Levenkov