Conversion between C # objects, files, and binary strings (byte arrays)

Source: Internet
Author: User

1. About this article

When transmitting information using the TCP (class TcpClient), UDP (class UdpClient) protocol under C #, you need to convert the information to an array of type byte to send. This article implements two conversions of object and byte arrays and a way to convert a file to a byte array. Data of the underlying type, which can be converted using functions in the Bitconverter class.

2.object and byte[] conversion: Serialization and deserialization using IFormatter serialize and deserialize

To implement this function, you need to refer to three namespaces first: System.IO, System.Runtime.Serialization, System.Runtime.Serialization.Formatters.Binary;

 <summary>///  tools: Converting between objects and binary streams/// </summary>class byteconverthelper{     /// <summary>    ///  convert an object to a byte array      /// </summary>    /// <param name= "obj" > Converted Object </param >    /// <returns> converted byte array </returns>    public  static byte[] object2bytes (object obj)     {         byte[] buff;        using  ( Memorystream ms = new memorystream ())         {             iformatter iformatter =  new binaryformatter ();             Iformatter.serialize (ms, obj);            buff = ms. GetBuffer ();        }         return buff;    }    /// <summary>     ///  convert a byte array to an object     /// </summary>    ///  <param name= "Buff" > converted byte array </param>    /// <returns> converted to Finished object </returns>    public static object bytes2object (Byte[] buff)     {        object obj;         using  (Memorystream ms = new memorystream (buff))          {             IFormatter iFormatter = new BinaryFormatter ();            obj =  Iformatter.deserialize (MS);        }         return obj;    }}

Invocation Example:

Suppose there is a structure with the Serializable attribute added:

 <summary>///  Test Structure/// </summary>[serializable]struct teststructure{     public string a; //variable a    public char b;    //variable b    public int c;    //variable c     /// <summary>    ///  Constructors     /// < /summary>    /// <param name= "Paraa" ></param>     /// <param name= "Parab" ></param>    /// <param  Name= "Parac" ></param>    public teststructure (String paraA, char  parab, int parac)     {        this . A = paraa;        this. B = parab;      &nbsP; this. c = parac;    }    /// <summary>     ///  output content in this structure     /// </summary>    ///  <returns></returns>    public string displayinfo ()      {        return string. Format ("a:{0}; B:{1}; C:{2} ",  this. A, this. B, this. C);     }}

Then call the following code to complete the transformation of this structure

static void Main (string[] args) {teststructure TsA = new Teststructure ("1234", ' 5 ', 6);    byte[] byttemp = byteconverthelper.object2bytes (TsA);    Console.WriteLine ("Array Length:" + byttemp.length);    Teststructure TsB = (teststructure) byteconverthelper.bytes2object (byttemp);    Console.WriteLine (Tsb.displayinfo ()); Console.ReadLine ();}

The output is:

It is important to note that, in this way, the transformation between a struct and a byte array must have a serializable attribute on the struct or class. Otherwise there will be an exception (SerializationException): "Assembly" XXX, version=1.0.0.0, culture=neutral, publickeytoken=null "type" xxx.xxx " Not marked as serializable "

In addition, this method produces a large byte array length

3. Convert an object to a byte array using the STRUCTURETOPTR and ptrtostructure functions of the Marshal class

To implement this function, you need to refer to the namespace first: System.Runtime.InteropServices

 <summary>///  tools: Converting between objects and binary streams/// </summary>class byteconverthelper{     /// <summary>    ///  convert an object to a byte array      /// </summary>    /// <param name= "obj" > Converted Object </param >    /// <returns> converted byte array </returns>    public  static byte[] object2bytes (object obj)     {         byte[] buff = new byte[marshal.sizeof (obj)];         intptr ptr = marshal.unsafeaddrofpinnedarrayelement (buff, 0) ;         marshal.structuretoptr (obj, ptr, true);         return buff;    }    ///  <summary>    ///  convert a byte array to an object     /// </summary>    ///  <param name= "Buff" > converted byte array </param>    /// <param  Name= "Typ" > Converted to Class name </param>    /// <returns> converted to Finished object </returns>     public static object bytes2object (Byte[] buff, type typ)     {        IntPtr ptr =  Marshal.unsafeaddrofpinnedarrayelement (buff, 0);         return  marshal.ptrtostructure (Ptr, typ);     }}

Invocation Example:

The existing structure is as follows (which is less characteristic serializable than the structure in the example above):

 <summary>///  Test Structure/// </summary>struct teststructure{     public string a; //variable a    public char b;   / /variable b    public int c;    //variable c    ///  <summary>    ///  Constructors     /// </summary>     /// <param name= "Paraa" ></param>    ///  <param name= "Parab" ></param>    /// <param name= "ParaC "></param>    public teststructure (String paraa, char parab,  int parac)     {        this. A = paraa;        this. B = parab;        this. C = paraC;    }    /// <summary>     ///  output content in this structure     /// </summary>    /// < Returns></returns>    public string displayinfo ()      {        return string. Format ("a:{0}; B:{1}; C:{2} ",  this. A, this. B, this. C);     }}

Call the following code to complete the conversion:

static void Main (string[] args) {teststructure TsA = new Teststructure ("1234", ' 5 ', 6);    byte[] byttemp = byteconverthelper.object2bytes (TsA);    Console.WriteLine ("Array Length:" + byttemp.length); Teststructure TsB = (teststructure) byteconverthelper.bytes2object (byttemp, Type.GetType ("ByteConverter2.TestStruct    Ure "));    Console.WriteLine (Tsb.displayinfo ()); Console.ReadLine ();}

To run the example:


As you can see, the array length is only 12, which is much shorter than the byte[] array converted in the example above, which is more space-saving

3. Using FileStream to convert a file to a byte array

To implement this feature, you need to reference the namespace first: System.IO

 <summary>///  tools: Converting between files and binary streams/// </summary>class filebinaryconverthelper{     /// <summary>    ///  convert a file to a byte array      /// </summary>    /// <param name= "Path" > File address </ Param>    /// <returns> converted byte array </returns>     Public static byte[] file2bytes (String path)     {         if (! File.exists (path))         {             return new byte[0];        }         fileinfo fi = new fileinfo (PATH);         byte[] buff = new byte[fi. Length]; &nbsP;      filestream fs = fi. OpenRead ();         fs. Read (Buff, 0, convert.toint32 (fs. Length));         fs. Close ();        return buff;    }     /// <summary>    ///  convert a byte array to a file and save to the specified address      /// </summary>    /// <param name= "Buff" >byte array </param >    /// <param name= "Savepath" > Save Address </param>     public static void bytes2file (Byte[] buff, string savepath)      {        if  (File.exists (savepath))          {             File.deleTe (Savepath);        }         Filestream fs = new filestream (savepath, filemode.createnew);         binarywriter bw = new binarywriter (FS);     &NBSP;&NBSP;&NBSP;&NBSP;BW. Write (Buff, 0, buff. Length);         bw. Close ();         fs. Close ();     }}

Assuming there is a file Test.txt, call the following code to write test.txt to a byte array and write the contents of the byte array to the file output.txt

static void Main (string[] args) {byte[] byttemp = filebinaryconverthelper.file2bytes ("test.txt");    Console.WriteLine ("Array Length:" + byttemp.length);    Filebinaryconverthelper.bytes2file (byttemp, "output.txt");    Console.WriteLine ("Output Complete"); Console.ReadLine ();}

Operation Result:

END

Conversion between C # objects, files, and binary strings (byte arrays)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.