1

is there anyway to convert object (or class) to byte[] ?

like System.IO.DriveInfo to byte[] ?

if so . how can I unconvert that ?

4 Answers 4

1
static void Main(string[] args) { using (var stream = new MemoryStream()) { // serialize object var formatter = new BinaryFormatter(); var foo = new Foo(); formatter.Serialize(stream, foo); // get a byte array // (thanks to Matt for more concise syntax) var bytes = stream.GetBuffer(); // deserialize object var foo2 = (Foo) formatter.Deserialize(stream); } } [Serializable] class Foo:ISerializable { public string data; #region ISerializable Members public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("data",data); } #endregion } 
Sign up to request clarification or add additional context in comments.

3 Comments

You can just grab the array out of the MemoryStream with GetBuffer()
how can I store bytes[] in stream for Deserialize ?
@pedram that's what the Serialize call does
0

If the class is Serializable you can use a BinaryFormatter to accomplish this. The followin code snippet can provide you with a start:

http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Object-to-byte-array.html

Comments

0

I think the term you are looking for is "serialization"

Resources:

Comments

0

You could use a BinaryFormatter to serialize an object to a MemoryStream, then get the bytes from that. BinaryFormatter can do the transformation back to object from byte[] array too (deserialization). The data will look very strange though. It is not the same as the memory image if that's what you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.