zoukankan      html  css  js  c++  java
  • C#配置文件管理

      最近在做项目的过程中用到配置文件,本文简要说明本人在项目过程中是如何使用配置文件的,目的是加深自己对配置文件管理的理解,以便在下次使用时能做到轻松自如。

      配置文件,顾名思义,是用户在使用系统或者软件时需要根据不同的状况手动配置的文件。在c#wpf项目中,配置文件一般有两种,一种是在系统中新建的配置文件即应用程序配置文件,命名一般习惯为App.config;另外一种则是根据需要自定义的配置文件,这类配置文件命名定义比较自由,同时内部的节点的设置等都比较随便,最主要的是满足需求。下面首先描述应用程序配置文件App.config。

    1、应用程序配置文件

    新建应用程序配置文件:

      选中工程名称,右键添加现有项选择应用程序配置文件,此次一般命名为App.config。

      在configuration中添加如下内容,此次是添加了两个字段。

    <appSettings>
          <add key="id" value ="13"/>
        <add key ="user" value ="24"/>
        </appSettings>

    读取配置文件内容:

      

      首先添加引用:system.configuration,并在代码添加using System.Configuration;

      读取字段值:string str1 = System.Configuration.ConfigurationManager.AppSettings["id"];

    应用程序配置文件的使用相对简单稳定,适合于一般的配置文件值的设置。但是如果需要经常的更改或者增加配置文件字段值,应用程序配置文件则显得较为繁琐。

    2、自定义配置文件

    使用场景:

      由于此类文件具有:1、可以手动更改配置文件中字段的值;2、能够保存最近输入字段的值。所以比较适合于在系统应用过程中需要经常变动的值,而且它的第二种功能因为能记住最近一次输入的值而显的尤为重要。

    新建自定义配置文件:

      选中工程名称右键添加新建项,选择文本文件并更改名称,此次暂定义为system.cfg。打开文件显示一个空的文件,此次添加如下:<configurationN  ServerAddress="192.273"  />。注:由于xml文件易于保存添加和更改,此处添加的xml文件格式。

    在代码中对配置文件进行更改和添加:

      在代码中加入一个字段:

    private string _ServerAddress;
            public string ServerAddress
            {
                get { return _ServerAddress; }
                set 
                {
                    this._ServerAddress = value;
                    NotifyPropertyChanged("ServerAddress");
                }
            }
    
    public event PropertyChangedEventHandler PropertyChanged;
            private void NotifyPropertyChanged(string propertyName)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
    View Code

      代码中定义xml的字段:

        public const string managerName = "configurationN";
            public const string configuration_ServerAdderss = "ServerAddress";

      初始化配置文件:

    public bool Load(string path)
            {
                bool ret = true;
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(path);
                    foreach (XmlNode node in doc.ChildNodes)
                    {
                        switch (node.Name)
                        {
                            case managerName:
                                this.LoadXMLNode(node);
                                break;
                        }
                    }
                }
                catch
                {
                    ret = false;
                }
                return ret;
            }
    
            public bool LoadXMLNode(XmlNode node)
            {
                bool ret = true;
                try
                {
                    Utils.ReadXMLAttribute(this, node.Attributes, configuration_ServerAdderss);
                }
                catch (Exception ex)
                {
                    ret = false;
                }
                return ret;
            }
    View Code

      保存配置文件:

    public bool Save(string path)
            {
                bool ret = true;
                try
                {
                    XmlDocument doc = new XmlDocument();
                    XmlNode node = doc.CreateNode(XmlNodeType.Element, managerName, null);
                    this.SaveXMLNode(doc, node);
                    doc.AppendChild(node);
                    doc.Save(path);
                }
                catch
                {
                    ret = false;
                }
                return ret;
            }
    
            public bool SaveXMLNode(XmlDocument xmlDoc, XmlNode node)
            {
                bool ret = true;
                try
                {
                    Utils.AppendXMLAttribute(node, xmlDoc, configuration_ServerAdderss, this.ServerAddress);
                }
                catch (Exception ex)
                {
                    ret = false;
                }
                return ret;
            }
    View Code

      上述过程中用到的读取和增加xml节点的方法:

    public static bool ReadXMLAttribute(object obj, XmlAttributeCollection attrs, string attributeName)
            {
                PropertyInfo tmp = null;
                try
                {
                    object[] args = new object[1];
                    Type ot = obj.GetType();
                    PropertyInfo pi = ot.GetProperty(attributeName);
                    tmp = pi;
                    if (pi.PropertyType.FullName == "System.String")
                    {
                        args[0] = attrs[attributeName].Value.ToString();
                        ot.InvokeMember(attributeName, System.Reflection.BindingFlags.SetProperty, null, obj, args);
                    }
                    else if (pi.PropertyType.BaseType.FullName == "System.Enum")
                    {
                        args[0] = Enum.Parse(pi.PropertyType, attrs[attributeName].Value);
                        ot.InvokeMember(attributeName, System.Reflection.BindingFlags.SetProperty, null, obj, args);
                    }
                    else if (pi.PropertyType.FullName == "System.Int32")
                    {
                        args[0] = Convert.ToInt32(attrs[attributeName].Value);
                        ot.InvokeMember(attributeName, System.Reflection.BindingFlags.SetProperty, null, obj, args);
                    }
    
                }
                catch (Exception ex)
                {
                    return false;
                }
                return true;
            }
    
            public static bool AppendXMLAttribute(XmlNode node, XmlDocument xmlDoc, string attributeName, object value)
            {
                try
                {
    
                    XmlAttribute attr = xmlDoc.CreateAttribute(attributeName);
                    if (value == null)
                    {
                        attr.Value = "";
                    }
                    else
                    {
                        attr.Value = value.ToString();
                    }
                    node.Attributes.Append(attr);
                }
                catch (Exception ex)
                {
                    return false;
                }
                return true;
            }
    View Code

    调用部分(wpf窗体):

    public MainWindow()
            {
                InitializeComponent();
                Start();
                this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString();
            }
    
            private void button1_Click(object sender, RoutedEventArgs e)
            {
                ConfigurationManager.Instance.ServerAddress = tb1.Text;
                ConfigurationManager.Instance.Save(ConstDefs.FileNames.SystemConfig);
            }
    
            private void Start()
            {
                ConfigurationManager.Instance.Load(ConstDefs.FileNames.SystemConfig);
            }
    View Code

      总结:自定义配置文件的格式一般为xml格式,在操作文件过程中,首先需要将配置文件的属性的复制到输出目录设置为如果较新则复制,然后初始化xml文件并读取节点值,在操作调用完毕后保存xml配置文件,则将保存最近输入的字段值,从而满足新建自定义配置文件的目的。

     3、

    最近看到一个写的非常好的配置项目,记录下来:

    int interval;
    var sInterval = ConfigurationManager.AppSettings["SInterval"];
    Interval = int.TryParse(sInterval, out interval) ? interval : 3000; //default 3000

      

      

    最新博客信息,请关注“小项目笔记”公众号;
  • 相关阅读:
    POJ 1953 World Cup Noise
    POJ 1995 Raising Modulo Numbers (快速幂取余)
    poj 1256 Anagram
    POJ 1218 THE DRUNK JAILER
    POJ 1316 Self Numbers
    POJ 1663 Number Steps
    POJ 1664 放苹果
    如何查看DIV被设置什么CSS样式
    独行DIV自适应宽度布局CSS实例与扩大应用范围
    python 从入门到精通教程一:[1]Hello,world!
  • 原文地址:https://www.cnblogs.com/ysyn/p/3359402.html
Copyright © 2011-2022 走看看