C#xml and binary conversion to each other

Source: Internet
Author: User

about why you need to convert: I have been in the game industry for 4 years, but the configuration file is the original XML file, what is the other person's binary file. About why a configuration file is converted to a binary file: mainly for the sake of secrecy, the next is to save space. But then again, when you use the binary file, , it takes more than one step to get information.

Moreover, in a game project may have multiple configuration files, I currently in the development of more than 100, then packaged into INI binary is very necessary.

Here's an example:

Conversion of xmltobin:xml to binary files

Family.xml:XML file


Xmltobin:

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Threading.Tasks;using System.IO;using System.Xml.Serialization;using  system.runtime.serialization.formatters.binary;namespace xmltobyte.ainy{    ///  <summary>    /// xml Format Conversion     /// </summary>     public class XMLToBin    {         //public string a =  "a";         private static xmltobin instance;        public  static xmltobin instance        {             get {                 if  (xmltobin.instance == null)  {                     xmltobin.instance = new  xmltobin ();                 }                return  XMLToBin.instance;             }             set { xmltobin.instance =  value; }        }         public xmltobin ()         {             if  (xmltobin.instance != null)              {                 InstanceNoInstantiationException exp =  new  Instancenoinstantiationexception (typeof (Xmltobin));                 console.writeline ( exp. Message);                 throw  exp;            }             else             {                 XMLToBin.instance = this;             }        }       &nBsp;/// <summary>        /// object to xml         /// </summary>         /// <typeparam name= "T" ></typeparam>         /// <param name= "obj" ></param>         /// <param name= "Path" ></param>        ///  <returns></returns>        public bool  Serializer<t> (Object obj, string path)         {             FileStream xmlfile =  New filestream (path, filemode.openorcreate);             //creating a serialized object              xmlserializer xml =  New xmlserializer (typeof (T));             try             {    //Serialized Objects                  xml. Serialize (xmlfile, obj);                 xmlfile. Close ();            }             catch  (InvalidOperationException)              {                 throw;             }            return true;         }        /// <summary>         /// XML to Object         /// </summary>        /// <typeparam  Name= "T" ></typeparam>        /// <param name= " Path "></param>        /// <returns></returns >        public static T Deserializer<T> ( String path)         {             try            {                 filestream xmlfile = new  FileStream (Path, filemode.open);                 xmlserializer xml = new xmlserializer (typeof (T));                 T t =  (T) Xml. Deserialize (xmlfile);                 xmlfile. Close ();                 return  t;            }             catch  (InvalidOperationException)              {                 throw;            }             catch  (FileNotFoundException)             { throw; }             finally             {            }         }        /// <summary>         /// Object to Bin         /// </summary>        /// <param  name= "obj" ></param>        /// <param name = "Path" ></param>        /// <returns></returns>         public bool binaryserializer (object obj, string  Path)         {             filestream stream = new filestream (path, filemode.openorcreate);             //creating a serialized object               BinaryFormatter bin = new  BinaryFormatter ();            try             {    //Serialized Objects                  bin. Serialize (stream, obj);       &nbSp;         stream.close ();             }             catch  (InvalidOperationException)              {                throw;             }             return true;        }         /// <summary>        // / bin to object        /// </summary>         /// <typeparam name= "T" ></typeparam>     &nbsP;   /// <param name= "Path" ></param>         /// <returns></returns>        public  T BinaryDeserializer<T> (String path)         {             try             {                 filestream binfile = new filestream (Path, FileMode.Open );                 Binaryformatter bin = new binaryformatter ();                 //Serialized Objects                   //xmlfile. Close ();                 t  t =  (t) bin. Deserialize (Binfile);                 binfile. Close ();                 return  t;            }             catch  (InvalidOperationException)              {                 throw;             }            catch  ( FileNotFoundException)              { throw; }            finally             {             }        }         /// <summary>        ///  Read Text          /// </summary>         /// <param name= "TargetPath" ></param>         /// <returns></returns>        public  String readcommon (String targetpath)         {             if  (File.exists (TargetPath))              {                 //using  (Streamreader sr = file.opentext (TargetPath))  //  Reading Chinese will be garbled                 string  bcStr =  "";                 using  (Streamreader sr = new streamreader (targetpath,  Unicodeencoding.getencoding ("GB2312"))  //  solve Chinese garbled problem                  {                     string readStr;                     while  (readstr &NBSP;=&NBSP;SR. ReadLine ())  != null)                      {                         bcStr = bcStr + readStr;                      }                  &NBSP;&NBSP;&NBSP;SR. Close ();                 }                 return  bcstr;            }             else            &nBsp {                 Console.WriteLine ("message ,  not found file {0}",  targetpath);                 return string. empty;            }         }    }}

Family.xml:

<?xml version= "1.0" encoding= "Utf-8"?><people> 

Test:

Using system;using system.collections.generic;using system.linq;using system.text;using  system.threading.tasks;using xmltobyte.ainy;namespace xmltobyte{    class  Program    {        static void  Main (String[] args)         {             string xml = xmltobin.instance.readcommon (".. /.. /res/family.xml ");             console.writeline (" Family.xml : {0} ",  xml);             console.writeline ("message --  converted to binary succeeded: {0}",  xmltobin.instance.binaryserializer (XML,   ". /.. /res/family.ini "));             //string json  =  "{PEOPEL={&NBSp [ husband={ name=\ "ainy\"  , age = \ "26\"  }, wife={ name=\ "snow\"  , age = \ "24\" &NBSP;}&NBSP;]&NBSP;}} ";             //console.writeline ("message --  converted to a binary file succeeded: {0}",  XMLToBin.Instance.BinarySerializer (json,  ". /.. /res/familyjson.ini "));             Console.WriteLine ("Family.ini : {0}",  xmltobin.instance.readcommon (".. /.. /res/family.ini "));             string axml  = XMLToBin.Instance.BinaryDeserializer<string> (".. /.. /res/family.ini ");             console.writeline (" message --  converted to a text file succeeded: {0} ",axml );             console.readkey ();         }    }} 

Note that both JSON and XML are available. Result:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/79/F7/wKioL1afS5vTZAGnAACIXoDzvqI820.png "title=" Qqa1.png "alt=" Wkiol1afs5vtzagnaacixodzvqi820.png "/>

Look at the results, the Chinese words have changed, the English also vaguely see the configuration information. So far, after all, China's game configuration a large number of Chinese. Also thanks to the Almighty Technical Forum, part of the code is to see from: http://www.cnblogs.com/jesszhu/ Archive/2013/08/22/3276556.html

If the reader has a better way, please do not enlighten.

This article is from the "Better_power_wisdom" blog, make sure to keep this source http://aonaufly.blog.51cto.com/3554853/1736885

C#xml and binary conversion to each other

Related Article

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.