Writing instances of arbitrary type in a MemoryStream in C #

In Delphi, you 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 contents of memory i in ms.

The .Net version of MemoryStream does not have this feature (neither managed nor unmanaged versions). I know .Net does not work on the same principles as Delphi in this regard.

How to do it in C #? I'm interested in "best practice" and the fastest methods.

+6
source share
3 answers

Try using BinaryWriter on top of a MemoryStream:

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

Note. Do not forget to delete streams and records / readers in real code, i.e. on using .

+4
source

Serialize your object into an array of bytes

 // 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 a MemoryStream to record it as needed

 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); 
+6
source

.NET streams are processed only with byte data.

To write any other data type, you will need an "endpiece":

  • BinaryWriter for writing primitive values ​​(int, double, string)
  • TextWriter to write char and strings using Encoding
  • Serializer (many moves) for writing objects

So in your case:

 var writer = new BinaryWriter(myStream); writer.Write(i); // writes 4 bytes only 
+2
source

Source: https://habr.com/ru/post/910474/


All Articles