温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#XML与二进制相互转换

发布时间:2020-08-06 03:33:12 来源:网络 阅读:3201 作者:Aonaufly 栏目:编程语言

关于为什么需要转换:本人步入Game行业已经4年了,但是配置文件要麽是原生的XML文件,要麽是别人的二进制文件.关于配置文件为啥要转换成二进制文件:主要是为了保密,其次才是节省空间.但是话又说回来了,使用二进制文件的时候,获取信息,需要多一步转化过程.

再者,在一个Game项目中可能有多个配置文件,本人目前在开发的有100多个,那么打包成ini二进制是很有必要的.

来个例子:

XMLToBin : XML 与 二进制文件的相互转换

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的格式转换
    /// </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);

            //创建序列化对象 
            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);
            //创建序列化对象 
            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 -- 转换成二进制文件成功:{0}", XMLToBin.Instance.BinarySerializer(xml, "../../res/family.ini"));
            //string json = "{peopel={ [ husband={ name=\"ainy\" , age = \"26\" }, wife={ name=\"snow\" , age = \"24\" } ] }}";
            //Console.WriteLine("Message -- 转换成二进制文件成功:{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 -- 转换成文本文件成功:{0}",aXml );
            Console.ReadKey();
        }
    }
}

注意到:其实Json和XML都可以.结果:

C#XML与二进制相互转换

看结果,中文的话都改变了,英文还隐隐约约看得到配置信息.目前就这样了,毕竟中国游戏配置一大片都是中文的.另外还要感谢万能的技术论坛,一部分代码是看来自:http://www.cnblogs.com/jesszhu/archive/2013/08/22/3276556.html

如果读者有更好的方法,请不灵赐教.

附件:http://down.51cto.com/data/2367316
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI