C#XML與二進制相互轉(zhuǎn)換

關于為什么需要轉(zhuǎn)換:本人步入Game行業(yè)已經(jīng)4年了,但是配置文件要麼是原生的XML文件,要麼是別人的二進制文件.關于配置文件為啥要轉(zhuǎn)換成二進制文件:主要是為了保密,其次才是節(jié)省空間.但是話又說回來了,使用二進制文件的時候,獲取信息,需要多一步轉(zhuǎn)化過程.

創(chuàng)新互聯(lián)公司專注于凌海企業(yè)網(wǎng)站建設,成都響應式網(wǎng)站建設公司,購物商城網(wǎng)站建設。凌海網(wǎng)站建設公司,為凌海等地區(qū)提供建站服務。全流程定制網(wǎng)站,專業(yè)設計,全程項目跟蹤,創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務

再者,在一個Game項目中可能有多個配置文件,本人目前在開發(fā)的有100多個,那么打包成ini二進制是很有必要的.

來個例子:

XMLToBin : XML 與 二進制文件的相互轉(zhuǎn)換

family.xml : XML文件


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的格式轉(zhuǎn)換
    /// </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;
            }
        }
        /// <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);

            //創(chuàng)建序列化對象 
            XmlSerializer xml = new XmlSerializer(typeof(T));
            try
            {    //序列化對象
                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);
            //創(chuàng)建序列化對象 
            BinaryFormatter bin = new BinaryFormatter();
            try
            {    //序列化對象
                bin.Serialize(Stream, obj);
                Stream.Close();
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            return true;
        }
        /// <summary>
        /// Bin to Object
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public T BinaryDeserializer<T>(string path)
        {
            try
            {
                FileStream binfile = new FileStream(path, FileMode.Open);

                BinaryFormatter bin = new BinaryFormatter();
                //序列化對象
                //xmlfile.Close();
                T t = (T)bin.Deserialize(binfile);
                binfile.Close();
                return t;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (FileNotFoundException)
            { throw; }
            finally
            {

            }
        }
        /// <summary>
        /// 讀取文本
        /// </summary>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public string ReadCommon(string targetPath)
        {
            if (File.Exists(targetPath))
            {
                //using (StreamReader sr = File.OpenText(targetPath)) // 讀中文將亂碼
                string bcStr = "";
                using (StreamReader sr = new StreamReader(targetPath, UnicodeEncoding.GetEncoding("GB2312"))) // 解決中文亂碼問題
                {
                    string readStr;
                    while ((readStr = sr.ReadLine()) != null)
                    {
                        bcStr = bcStr + readStr;
                    }
                    sr.Close();
                }
                return bcStr;
            }
            else
            {
                Console.WriteLine("Message , 沒有找到文件{0}", targetPath);
                return string.Empty;
            }
        }
    }
}

family.xml:

<?xml version="1.0" encoding="utf-8" ?>
<people>
  <husband>
    <attribute name ="胡Ainy" age ="26" ></attribute>
  </husband>
  <wife>
    <attribute name ="snow" age="24"></attribute>
  </wife>
  <daughter>
    <attribute name ="ms" age="1"></attribute>
  </daughter>
</people>

測試:

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 -- 轉(zhuǎn)換成二進制文件成功:{0}", XMLToBin.Instance.BinarySerializer(xml, "../../res/family.ini"));
            //string json = "{peopel={ [ husband={ name=\"ainy\" , age = \"26\" }, wife={ name=\"snow\" , age = \"24\" } ] }}";
            //Console.WriteLine("Message -- 轉(zhuǎn)換成二進制文件成功:{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 -- 轉(zhuǎn)換成文本文件成功:{0}",aXml );
            Console.ReadKey();
        }
    }
}

注意到:其實Json和XML都可以.結(jié)果:

C#XML與二進制相互轉(zhuǎn)換

看結(jié)果,中文的話都改變了,英文還隱隱約約看得到配置信息.目前就這樣了,畢竟中國游戲配置一大片都是中文的.另外還要感謝萬能的技術論壇,一部分代碼是看來自:http://www.cnblogs.com/jesszhu/archive/2013/08/22/3276556.html

如果讀者有更好的方法,請不靈賜教.

附件:http://down.51cto.com/data/2367316

本文題目:C#XML與二進制相互轉(zhuǎn)換
分享路徑:http://www.muchs.cn/article6/geesig.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供服務器托管、靜態(tài)網(wǎng)站、面包屑導航自適應網(wǎng)站、電子商務網(wǎng)站設計公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設計公司