C# 对ini文件的序列化和反序列化

 1.对ini文件进行序列化和反序列化

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    public class IniDeserialize<T> where T : class, new()
    {
        /// <summary>
        /// 若ini文件中无对应值,就提取默认对象中的值
        /// </summary>
        T _defaultT;

        /// <summary>
        /// 序列化后的对象
        /// </summary>
        public T Value { get; set; }

        IniRW _iniRW;
        public IniDeserialize(string path, T defaultT)
        {
            _iniRW = new IniRW(path);
            _defaultT = defaultT;
            Deserialize();
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        bool Deserialize()
        {
            Value = new T();
            Type tInfo = Value.GetType();
            string section = tInfo.Name;
            foreach (PropertyInfo p in tInfo.GetProperties())
            {
                string key = p.Name;
                string iniValue = _iniRW.ReadString(section, key);
                if (iniValue == string.Empty)
                {
                    PropertyInfo pd = _defaultT.GetType().GetProperty(key);
                    iniValue = pd.GetValue(_defaultT, null) as string;
                }
                object value = iniValue.Format(p.PropertyType);
                p.SetValue(Value, value, null);
            }
            return true;
        }

        /// <summary>
        /// 序列化保存
        /// </summary>
        /// <returns></returns>
        public bool Serialize()
        {
            Type tInfo = Value.GetType();
            string section = tInfo.Name;
            foreach (PropertyInfo p in tInfo.GetProperties())
            {
                string key = p.Name;
                object value = p.GetValue(Value, null);
                _iniRW.WriteValue(section, key, value);
            }
            return true;
        }


    }

 2.对ini文件的读写

    public class IniRW : IniUse
    {
        public string IniPath;

        public IniRW(string path)
        {
            IniPath = path;
        }

        public virtual bool WriteValue(string section, string key, object value)
        {
            string v = value == null ? "" : value.ToString();
            long ret = WritePrivateProfileString(section, key, v, IniPath);
            return true;
        }

        public virtual string ReadString(string section, string key)
        {
            StringBuilder sb = new StringBuilder(255);
            string def = string.Empty;
            int ret = GetPrivateProfileString(section, key, def, sb, 255, IniPath);
            return ret == 0 ? def : sb.ToString();
        }

        public int ReadInt(string section, string key)
        {
            return (int)ReadDouble(section, key);
        }

        public short ReadShort(string section, string key)
        {
            return (short)ReadDouble(section, key);
        }

        public byte ReadByte(string section, string key)
        {
            return (byte)ReadDouble(section, key);
        }

        public double ReadDouble(string section, string key)
        {
            double res = 0;
            string sb = ReadString(section, key);
            double.TryParse(sb, out res);
            return res;
        }

        public bool ReadBool(string section, string key)
        {
            bool res = false;
            string sb = ReadString(section, key).Trim();
            if (sb == "1")
            {
                return true;
            }
            else if (sb == "0")
            {
                return false;
            }
            bool.TryParse(sb, out res);
            return res;
        }


    }

3.调用 kernel32 对ini的读写

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices; //WinAPI引用命名空间

    /// <summary>
    /// 对ini配置文件读写,写时文件不存在会自动创建(不会自动创建文件夹)
    /// </summary>
    public class IniUse
    {
        [DllImport("kernel32")]
        public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        /// <summary>
        /// 从ini文件中获取键值  不存在则自动创建 若不存在键时返回def默认值,当不存在且def为空值时才返回0,否则为1  ps:文件打开的状态下都可以读取
        /// </summary>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <param name="def"></param>
        /// <param name="retVal"></param>
        /// <param name="size"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

    }

4.将读取到的字符串转换为对应的类型 

        using System;
        using System.ComponentModel;


        /// <summary>
        /// 将字符串格式化成指定的数据类型
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object Format(this string str, Type type)
        {
            if (string.IsNullOrEmpty(str))
                return null;
            if (type == null)
                return str;
            if (type.IsArray)
            {
                Type elementType = type.GetElementType();
                string[] strs = str.Split(new char[] { ';' });
                Array array = Array.CreateInstance(elementType, strs.Length);
                for (int i = 0, c = strs.Length; i < c; ++i)
                {
                    array.SetValue(ConvertSimpleType(strs[i], elementType), i);
                }
                return array;
            }
            return ConvertSimpleType(str, type);
        }

        private static object ConvertSimpleType(object value, Type destinationType)
        {
            object returnValue;
            if ((value == null) || destinationType.IsInstanceOfType(value))
            {
                return value;
            }
            string str = value as string;
            if ((str != null) && (str.Length == 0))
            {
                return null;
            }
            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            bool flag = converter.CanConvertFrom(value.GetType());
            if (!flag)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (!flag && !converter.CanConvertTo(destinationType))
            {
                throw new InvalidOperationException("无法转换成类型:" + value.ToString() + "==>" + destinationType);
            }
            try
            {
                returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, destinationType);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("类型转换出错:" + value.ToString() + "==>" + destinationType, e);
            }
            return returnValue;
        }

    }

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bridge_go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值