C#配置文件管理
最近在做项目的过程中用到配置文件,本文简要说明本人在项目过程中是如何使用配置文件的,目的是加深自己对配置文件管理的理解,以便在下次使用时能做到轻松自如。
配置文件,顾名思义,是用户在使用系统或者软件时需要根据不同的状况手动配置的文件。在c#wpf项目中,配置文件一般有两种,一种是在系统中新建的配置文件即应用程序配置文件,命名一般习惯为App.config;另外一种则是根据需要自定义的配置文件,这类配置文件命名定义比较自由,同时内部的节点的设置等都比较随便,最主要的是满足需求。下面首先描述应用程序配置文件App.config。
1、应用程序配置文件
新建应用程序配置文件:
选中工程名称,右键添加现有项选择应用程序配置文件,此次一般命名为App.config。
在configuration中添加如下内容,此次是添加了两个字段。
<appSettings>
<add key="id" value =""/>
<add key ="user" value =""/>
</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));
}
}
代码中定义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;
}
保存配置文件:
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;
}
上述过程中用到的读取和增加xml节点的方法:
public static bool ReadXMLAttribute(object obj, XmlAttributeCollection attrs, string attributeName)
{
PropertyInfo tmp = null;
try
{
object[] args = new object[];
Type ot = obj.GetType();
PropertyInfo pi = ot.GetProperty(attributeName);
tmp = pi;
if (pi.PropertyType.FullName == "System.String")
{
args[] = attrs[attributeName].Value.ToString();
ot.InvokeMember(attributeName, System.Reflection.BindingFlags.SetProperty, null, obj, args);
}
else if (pi.PropertyType.BaseType.FullName == "System.Enum")
{
args[] = 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[] = 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;
}
调用部分(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);
}
总结:自定义配置文件的格式一般为xml格式,在操作文件过程中,首先需要将配置文件的属性的复制到输出目录设置为如果较新则复制,然后初始化xml文件并读取节点值,在操作调用完毕后保存xml配置文件,则将保存最近输入的字段值,从而满足新建自定义配置文件的目的。
3、
最近看到一个写的非常好的配置项目,记录下来:
int interval;
var sInterval = ConfigurationManager.AppSettings["SInterval"];
Interval = int.TryParse(sInterval, out interval) ? interval : ; //default 3000
C#配置文件管理的更多相关文章
- Linux安装LAMP开发环境及配置文件管理
Linux主要分为两大系发行版,分别是RedHat和Debian,lamp环境的安装和配置也会有所不同,所以分别以CentOS 7.1和Ubuntu 14.04做为主机(L) Linux下安装软件,最 ...
- Python-day3作业-haproxy配置文件管理脚本
#!/usr/bin/env python import os,sys,time,re,prettytable,json from collections import defaultdict,Ord ...
- 【C#进阶系列】03 配置文件管理与程序集的引用版本重定向
先来点与标题不相关的: CLR支持两种程序集:弱命名程序集和强命名程序集. 两者的区别在于强命名程序集使用发布者的公钥和私钥进行签名.由于程序集被唯一性地标识,所以当应用程序绑定到强命名程序集时,CL ...
- 死磕salt系列-salt 配置文件管理
SLS是Salt State系统的核心,用来描述系统的目标状态,使用YAML语言书写.被用作配置文件管理. SLS文件 sls配置文件分为两种类型 top.sls 这是所有配置文件的入口 sls 这是 ...
- disconf实践(四)基于注解的分布式配置文件管理,自动reload
上一篇讲解了基于xml的自动reload的分布式配置文件管理,这一篇讲解基于注解的自动reload的方式(基于disconf实践二). 1. 修改spring配置文件 <?xml version ...
- disconf实践(三)基于XML的分布式配置文件管理,自动reload
上一篇介绍了基于xml的非自动reload的分布式配置文件管理,这一篇介绍自动reload的方式(基于disconf实践二). 1. 修改RedisConfig.java package org.sp ...
- Haproxy安装部署文档及多配置文件管理方案
一.部署安装 二.软件配置 三.系统服务 四.日志配置 五.小结 文章目录 最近我在负责一个统一接入层的建设项目,涉及到 Haproxy 和 ospf 的运维部署,本文分享一下我在部署 Haproxy ...
- CentOS 7配置LNMP开发环境及配置文件管理
安装并配置MySQL 5.6 从CentOS从7.x开始默认使用MariaDB.MariaDB完全兼容MySQL,包括API和命令行.但是很多时候我们还是会想要安装MySQL,所以不能直接通过yum命 ...
- apache 配置文件管理
1. Apache配置系统 从整体来看apache的配置系统包括三个部分: (1) 配置文件:比如 httpd.conf .htaccess (2) 配置指令:在配置文件 httpd.conf ...
随机推荐
- android自定义radiobutton样式文字颜色随选中状态而改变
主要是写一个 color selector 在res/建一个文件夹取名color res/color/color_radiobutton.xml <selector xmlns:android= ...
- Android中手机号、车牌号正则表达式
手机号 手机号的号段说明转载自:国内手机号码的正则表达式|蜗牛的积累 手机名称有GSM:表示只支持中国联通或者中国移动2G号段(130.131.132.134.135.136.137.138.139. ...
- [原创]cin、cin.get()、cin.getline()、getline()、gets()、getchar()的区别
这几个输入函数经常搞不清具体特点和用法,这里稍作总结 一.cin>> 1.最基本用法,输入一个变量值 2.输入字符串,遇“空格”.“TAB”.“回车”结束,比如输入“hello world ...
- [转]移动web开发中meta标签作用
今天在尝试做移动页面的时候遇到了一个问题,<meta content="telephone=no,email=no" name="format-detection& ...
- GoLang 的 daemonize 实现
func daemonize(cmd string, args []string, pipe io.WriteCloser) error { pid, _, sysErr := syscall.Raw ...
- Centos源码安装Python3
CentOS7默认安装了python2.7.5,当需要使用python3的时候,可以手动下载Python源码后编译安装. 下载python(https://www.python.org/ftp/pyt ...
- Linux由管道组成的值得学习的命令
1.Linux查找不以#开头的行的命令如:cat /etc/vsftpd/vsftpd.conf | grep -v "#"
- java 8-5 抽象
1. 抽象类的概述: 动物不应该定义为具体的东西,而且动物中的吃,睡等也不应该是具体的. 我们把一个不是具体的功能称为抽象的功能,而一个类中如果有抽象的功能,该类必须是抽象类. 抽象类的特点: A:抽 ...
- f2fs解析(六)
f2fs中有对一个bitmap进行操作的函数,感觉很巧妙,和大家分享一下: 1333 static inline void f2fs_change_bit(unsigned int nr, char ...
- C#中的bitmap类和图像像素值获取方法
一.Bitmap类 Bitmap对象封装了GDI+中的一个位图,此位图由图形图像及其属性的像素数据组成.因此Bitmap是用于处理由像素数据定义的图像的对象.该类的主要方法和属性如下: 1. GetP ...