is there anyway to convert object (or class) to byte[] ?
like System.IO.DriveInfo to byte[]开发者_高级运维 ?
if so . how can I unconvert that ?
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
}
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
I think the term you are looking for is "serialization"
Resources:
- http://www.codeproject.com/KB/cs/objserial.aspx
- http://blog.kowalczyk.info/article/Serialization-in-C.html
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.
精彩评论