保存类中变量或属性到XML配置文件

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml;
using System.Reflection;

namespace MasterCom.Util
{
    [System.AttributeUsage(System.AttributeTargets.Field |
                       System.AttributeTargets.Property)]
    public class NonSaveConfig : System.Attribute
    { }

    /// <summary>
    /// 配置文件,用来保存类的Field和Propertie为XML文件
    /// 只保存public 的Field 和 有get和set的Propertie
    /// 如果存在[NonSaveConfig]属性则不保存
    /// by:Gene
    /// </summary>
    public class AConfig
    {
        public virtual string ConfigFile
        {
            get
            {
                return System.Windows.Forms.Application.StartupPath + "/config/" + this.GetType().Name + ".xml";
            }
        }

        public virtual void Load()
        {
            if (!System.IO.File.Exists(ConfigFile)) return;
            MyXmlConfigFile configFile = new MyXmlConfigFile(ConfigFile);
            try
            {
                ConfigParames = configFile.GetItemValue(this.GetType().Name, "ConfigParames") as Dictionary<string, object>;
            }
            catch { }
        }

        public virtual void Save()
        {
            MyXmlConfigFile configFile = new MyXmlConfigFile();
            XmlElement con = configFile.AddConfig(this.GetType().Name);
            configFile.AddItem(con, "ConfigParames", ConfigParames);
            configFile.Save(ConfigFile);
        }

        public virtual Dictionary<string, object> ConfigParames
        {
            get
            {
                Dictionary<string, object> objs = new Dictionary<string, object>();
                foreach (FieldInfo fi in this.GetType().GetFields())
                {
                    if (fi.Name.Equals("ConfigParames") || fi.FieldType.Equals(this.GetType()))
                    {
                        continue;
                    }
                    else
                    {
                        object obj = fi.GetValue(this);
                        if (IsNeedSave(fi.GetCustomAttributes(true)))
                            objs.Add(fi.Name, getGetData(obj));
                    }
                }
                foreach (PropertyInfo pi in this.GetType().GetProperties())
                {
                    if (pi.Name.Equals("ConfigParames") || pi.DeclaringType.Equals(this.GetType()))
                    {
                        continue;
                    }
                    else
                    {
                        object obj = pi.GetValue(this, null);
                        if (IsNeedSave(pi.GetCustomAttributes(true)) && pi.CanRead && pi.CanWrite)
                            objs.Add(pi.Name, getGetData(obj));
                    }
                }
                return objs;
            }
            set
            {
                if (value == null) return;
                foreach (FieldInfo fi in this.GetType().GetFields())
                {
                    if (!value.ContainsKey(fi.Name) || !fi.IsPublic) continue;
                    fi.SetValue(this, getSetData(fi.FieldType, value[fi.Name]));
                }
                foreach (PropertyInfo pi in this.GetType().GetProperties())
                {
                    if (!value.ContainsKey(pi.Name) || !(pi.CanRead && pi.CanWrite)) continue;
                    pi.SetValue(this, getSetData(pi.DeclaringType, value[pi.Name]), null);
                }
            }
        }

        private object getSetData(Type type, object obj2)
        {
          
            object obj = null;
            try
            {
                obj = System.Activator.CreateInstance(type);
            }
            catch { }
            try
            {
                if (obj == null)
                {
                    System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                    obj = System.Activator.CreateInstance(assembly.FullName, type.FullName);
                }
            }
            catch { }
            if (obj is AConfig)
            {
                AConfig idc = obj as AConfig;
                idc.ConfigParames = obj2 as Dictionary<string, object>;
                return idc;
            }
            else if (obj is IList && obj2 is IList)
            {
                IList idc = obj as IList;
                foreach (object obj1 in (IList)obj2)
                {
                    idc.Add(getSetData(type.GetGenericArguments()[0], obj1));
                }
                return idc;
            }
            else if (obj is Array && obj2 is Array)
            {
                Array idc = obj as Array;
                for (int i = 0; i < idc.Length; i++)
                {
                    idc.SetValue(getSetData(type.GetGenericArguments()[0], ((Array)obj2).GetValue(i)), i);
                }
                return idc;
            }
            else if (obj is IDictionary && obj2 is Array)
            {
                IDictionary idc = obj as IDictionary;
                foreach (object obj1 in ((IDictionary)obj2).Keys)
                {
                    idc.Add(obj1.ToString(), getSetData(type.GetGenericArguments()[1], ((IDictionary)obj2)[obj1]));
                }
                return idc;
            }
            else
                return obj2;
        }

        private object getGetData(object obj)
        {
            if (obj is AConfig)
            {
                return ((AConfig)obj).ConfigParames;
            }
            else if (obj is IList)
            {
                List<object> objs = new List<object>();
                foreach (object obj2 in (IList)obj)
                {
                    objs.Add(getGetData(obj2));
                }
                return objs;
            }
            else if (obj is Array)
            {
                object[] objs = new object[((Array)obj).Length];
                for (int i = 0; i < objs.Length; i++)
                {
                    objs.SetValue(getGetData(objs.GetValue(i)), i);
                }
                return objs;
            }
            else if (obj is IDictionary)
            {
                Dictionary<string, object> objs = new Dictionary<string, object>();
                IDictionary ids = obj as IDictionary;
                foreach (object obj2 in ids.Keys)
                {
                    objs.Add(obj2.ToString(), getGetData(obj2));
                }
                return objs;
            }
            else
                return obj;
        }

        private bool IsNeedSave(object[] attrs)
        {
            foreach (System.Attribute attr in attrs)
            {
                if (attr is NonSaveConfig)
                {
                    return false;
                }
            }
            return true;
        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;

namespace MasterCom.Util
{
     /// <summary>
     /// by:Gene
     /// </summary>
    public class MyXmlConfigFile
    {
        public delegate object GetItemValueObject(MyXmlConfigFile configFile, XmlElement item, string typeName);

        public delegate XmlElement AddItemObject(MyXmlConfigFile configFile, XmlElement config, string name, object value);

        public MyXmlConfigFile()
        {
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, null));
            doc.AppendChild(doc.CreateElement(TagConfigs));
        }

         public MyXmlConfigFile(string filePath)
        {
            this.filePath = filePath;
            try
            {
                doc.Load(filePath);
            }
            catch
            {
            }
        }

        public XmlElement AddConfig(string name)
        {
            XmlElement config = doc.CreateElement(TagConfig);
            AddNameAttribute(config, name);
            doc.DocumentElement.AppendChild(config);
            return config;
        }

        public XmlElement AddItem(XmlElement config)
        {
            XmlElement item = doc.CreateElement(TagItem);
            config.AppendChild(item);
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name)
        {
            XmlElement item = AddItem(config);
            if (name != null && name.Length > 0)
            {
                AddNameAttribute(item, name);
            }
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, Type type)
        {
            XmlElement item = AddItem(config, name);
            AddTypeAttribute(item, type);
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, string value)
        {
            XmlElement item = AddItem(config, name, typeof(string));
            if (value != null && value.Length > 0)
            {
                item.AppendChild(doc.CreateTextNode(value));
            }
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, string value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, int value)
        {
            XmlElement item = AddItem(config, name, typeof(int));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, int value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, long value)
        {
            XmlElement item = AddItem(config, name, typeof(long));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, long value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, float value)
        {
            XmlElement item = AddItem(config, name, typeof(float));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, float value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, double value)
        {
            XmlElement item = AddItem(config, name, typeof(double));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, decimal value)
        {
            XmlElement item = AddItem(config, name, typeof(decimal));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, double value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, char value)
        {
            XmlElement item = AddItem(config, name, typeof(char));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, char value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, bool value)
        {
            XmlElement item = AddItem(config, name, typeof(bool));
            item.AppendChild(doc.CreateTextNode(value.ToString()));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, bool value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem(XmlElement config, string name, System.Drawing.Color value)
        {
            XmlElement item = AddItem(config, name, typeof(System.Drawing.Color));
            item.AppendChild(doc.CreateTextNode(value.A+","+value.R+","+value.G+","+value.B));
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, System.Drawing.Color value, AddItemObject callBack)
        {
            return AddItem(config, name, value);
        }

        public XmlElement AddItem<T>(XmlElement config, string name, IList<T> value)
        {
            return AddItem(config, name, value, null);
        }

        public XmlElement AddItem<T>(XmlElement config, string name, List<T> value, AddItemObject callBack)
        {
            XmlElement item = AddItem(config, name, typeof(IList));
            if (value != null && value.Count > 0)
            {
                foreach (T childValue in value)
                {
                    AddItem(item, null, childValue, callBack);
                }
            }
            return item;
        }

        public XmlElement AddItem<K, V>(XmlElement config, string name, Dictionary<K, V> value)
        {
            return AddItem(config, name, value, null);
        }

        public XmlElement AddItem<K, V>(XmlElement config, string name, Dictionary<K, V> value, AddItemObject callBack)
        {
            XmlElement item = AddItem(config, name, typeof(IDictionary));
            if (value != null && value.Count > 0)
            {
                foreach (K key in value.Keys)
                {
                    V childValue = value[key];
                    XmlElement itemChild = AddItem(item, null, childValue, callBack);
                    AddKeyAttribute(itemChild, key.ToString());
                }
            }
            return item;
        }

        public XmlElement AddItem(XmlElement config, string name, object value)
        {
            return AddItem(config, name, value, null);
        }

        public XmlElement AddItem(XmlElement config, string name, object value, AddItemObject callBack)
        {
            XmlElement item = null;
            if (value != null)
            {
                if (value is string)
                {
                    item = AddItem(config, name, (string)value);
                }
                else if (value is int)
                {
                    item = AddItem(config, name, (int)value);
                }
                else if (value is long)
                {
                    item = AddItem(config, name, (long)value);
                }
                else if (value is float)
                {
                    item = AddItem(config, name, (float)value);
                }
                else if (value is double)
                {
                    item = AddItem(config, name, (double)value);
                }
                else if (value is decimal)
                {
                    item = AddItem(config, name, (decimal)value);
                }
                else if (value is char)
                {
                    item = AddItem(config, name, (char)value);
                }
                else if (value is bool)
                {
                    item = AddItem(config, name, (bool)value);
                }
                else if (value is System.Drawing.Color)
                {
                    item = AddItem(config, name, (System.Drawing.Color)value);
                }
                else if (value is IList)
                {
                    IList list = (IList)value;
                    item = AddItem(config, name, typeof(IList));
                    if (value != null && list.Count > 0)
                    {
                        foreach (object childValue in list)
                        {
                            AddItem(item, null, childValue, callBack);
                        }
                    }
                }
                else if (value is IDictionary)
                {
                    IDictionary dictionary = (IDictionary)value;
                    item = AddItem(config, name, typeof(IDictionary));
                    if (value != null && dictionary.Count > 0)
                    {
                        foreach (object key in dictionary.Keys)
                        {
                            object childValue = dictionary[key];
                            XmlElement itemChild = AddItem(item, null, childValue, callBack);
                            AddKeyAttribute(itemChild, key.ToString());
                        }
                    }
                }
                else if (callBack != null)
                {
                    item = callBack(this, config, name, value);
                }
                else
                {
                    item = AddItem(config, name, value.GetType());
                }
            }
            else
            {
                item = AddItem(config, name);
            }
            return item;
        }

        public XmlAttribute AddNameAttribute(XmlElement item, string name)
        {
            return AddAttribute(item, TagName, name);
        }

        public XmlAttribute AddTypeAttribute(XmlElement item, Type type)
        {
            return AddAttribute(item, TagTypeName, type.Name);
        }

        public XmlAttribute AddKeyAttribute(XmlElement item, string key)
        {
            return AddAttribute(item, TagKey, key);
        }

        public XmlAttribute AddAttribute(XmlElement item, string name, string value)
        {
            XmlAttribute attribute = doc.CreateAttribute(name);
            attribute.Value = value;
            item.Attributes.Append(attribute);
            return attribute;
        }

        public XmlElement GetConfig(string name)
        {
            foreach (XmlElement config in doc.DocumentElement.ChildNodes)
            {
                if (name != null && name.Equals(config.Attributes[TagName].Value))
                {
                    return config;
                }
            }
            return null;
        }

        public XmlElement GetItem(XmlElement config, string name)
        {
            if (config != null)
            {
                foreach (XmlElement item in config.ChildNodes)
                {
                    if (name != null && name.Equals(item.Attributes[TagName].Value))
                    {
                        return item;
                    }
                }
            }
            return null;
        }

        public XmlElement GetItem(string configName, string ItemName)
        {
            return GetItem(GetConfig(configName), ItemName);
        }

        public object GetItemValue(string configName, string itemName)
        {
            return GetItemValue(configName, itemName, null);
        }

        public object GetItemValue(string configName, string itemName, GetItemValueObject callBack)
        {
            return GetItemValue(GetConfig(configName), itemName, callBack);
        }

        public object GetItemValue(XmlElement config, string itemName)
        {
            return GetItemValue(config, itemName, null);
        }

        public object GetItemValue(XmlElement config, string itemName, GetItemValueObject callBack)
        {
            return GetItemValue(GetItem(config, itemName), callBack);
        }

        public object GetItemValue(XmlElement item)
        {
            return GetItemValue(item, (GetItemValueObject)null);
        }

        public object GetItemValue(XmlElement item, GetItemValueObject callBack)
        {
            if (item != null && item.Attributes[TagTypeName] != null)
            {
                string typeName = item.Attributes[TagTypeName].Value;
                if (typeName != null)
                {
                    if (typeName.Equals(typeof(string).Name))
                    {
                        return item.FirstChild == null ? null : item.FirstChild.InnerText;
                    }
                    else if (typeName.Equals(typeof(int).Name))
                    {
                        return item.FirstChild == null ? null : (object)int.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(long).Name))
                    {
                        return item.FirstChild == null ? null : (object)long.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(float).Name))
                    {
                        return item.FirstChild == null ? null : (object)float.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(double).Name))
                    {
                        return item.FirstChild == null ? null : (object)double.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(decimal).Name))
                    {
                        return item.FirstChild == null ? null : (object)decimal.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(char).Name))
                    {
                        return item.FirstChild == null ? null : (object)char.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(bool).Name))
                    {
                        return item.FirstChild == null ? null : (object)bool.Parse(item.FirstChild.InnerText);
                    }
                    else if (typeName.Equals(typeof(System.Drawing.Color).Name))
                    {
                        if (item.FirstChild == null) return null;
                        string[] strs = item.FirstChild.InnerText.Split(',');
                        if (strs.Length < 4) return null;
                        System.Drawing.Color col = System.Drawing.Color.FromArgb(
                            int.Parse(strs[0]),
                            int.Parse(strs[1]),
                            int.Parse(strs[2]),
                            int.Parse(strs[3]));
                        return col;
                    }
                    else if (typeName.Equals(typeof(IList).Name))
                    {
                        List<object> value = new List<object>();
                        foreach (XmlElement itemChild in item.ChildNodes)
                        {
                            object childValue = GetItemValue(itemChild, callBack);
                            value.Add(childValue);
                        }
                        return value;
                    }
                    else if (typeName.Equals(typeof(IDictionary).Name))
                    {
                        Dictionary<string, object> value = new Dictionary<string, object>();
                        foreach (XmlElement itemChild in item.ChildNodes)
                        {
                            string key = itemChild.Attributes[TagKey].InnerText;
                            object childValue = GetItemValue(itemChild, callBack);
                            value[key] = childValue;
                        }
                        return value;
                    }
                }
                if (callBack != null)
                {
                    return callBack(this, item, typeName);
                }
            }
            return null;
        }

        public bool Load()
        {
            try
            {
                doc.Load(filePath);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public bool Save()
        {
            try
            {
                new System.IO.FileInfo(filePath).Directory.Create();
                doc.Save(filePath);
            }
            catch
            {
                return false;
            }
            return true;
        }

        public bool Save(string filePath)
        {
            this.filePath = filePath;
            return Save();
        }

        private static string TagConfigs = "Configs";

        private static string TagConfig = "Config";

        private static string TagItem = "Item";

        private static string TagName = "name";

        private static string TagTypeName = "typeName";

        private static string TagKey = "key";

        private XmlDocument doc = new XmlDocument();

        private string filePath;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值