Config配置文件读写
config文件读写操作(文字说明附加在程序中)
App.config文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--自定义结点(为正常注册,将此节点放在第一)-->
<configSections>
<section name="Node1" type="Config.Test1,Config"/> <!--命名空间.类名,类名-->
<section name="Node2" type="Config.Test2,Config"/>
<section name="Node3" type="Config.Test3,Config"/>
<section name="Node4" type="Config.Test4,Config"/>
</configSections>
<Node1 Property1="属性1" Property2="属性2"></Node1>
<Node2>
<Property Property1="属性1" Property2="属性2"></Property>
</Node2>
<Node3>
<T1>
<!--CDATA可以包含比较长的字符串,且可以包含HTML代码段,这样针对特殊字符的存放也比较方便。-->
<![CDATA[
长字符串在此设置
]]>
</T1>
<T2>
<![CDATA[
<html><head>HTML代码</head></html>
]]>
</T2>
</Node3>
<Node4>
<add key="" value="test1"></add>
<add key="" value="test2"></add>
<add key="" value="test3"></add>
<add key="" value="test4"></add>
</Node4>
<!--connectionStrings连接数据库的配置-->
<connectionStrings>
<add name="ConString" connectionString="server=.;database=DB;uid=sa;pwd=123456"/>
<!--或 没有密码的连接-->
<!--add name="ConnStr" connectionString="Data Source=PC-201307122356\SQLEXPRESS;Initial Catalog=DZServe; Integrated Security=SSPI "/-->
</connectionStrings>
<!--appSettings连接数据库的配置或读取配置值-->
<appSettings>
<add key="AppString" value="server=.;database=DB;uid=sa;pwd=123456"/>
<!--或 没有密码的连接-->
<!--add key="AppString" value="Data Source=PC-201307122356\SQLEXPRESS;Initial Catalog=DZServe; Integrated Security=SSPI "/-->
</appSettings>
</configuration>
自定义结点1(Node1)的类Test1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration; namespace Config
{
//自定义一个Test类,以ConfigurationSection为基类,各个属性加上[ConfigurationProperty]
public class Test1:ConfigurationSection
{
[ConfigurationProperty("Property1")]
public string Property1
{
get { return this["Property1"].ToString(); }
set { this["Property1"] = value; }
} [ConfigurationProperty("Property2")]
public string Property2
{
get { return this["Property2"].ToString(); }
set { this["Property2"] = value; }
}
}
}
自定义结点2(Node2)的类Test2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration; namespace Config
{
public class Test2:ConfigurationSection
{
[ConfigurationProperty("Property",IsRequired=true)]
public SectionElement Property
{
get{ return (SectionElement)this["Property"];}
} public class SectionElement:ConfigurationElement
{
[ConfigurationProperty("Property1", IsRequired = true)]
public string Property1
{
get { return this["Property1"].ToString(); }
set { this["Property1"] = value; }
}
[ConfigurationProperty("Property2", IsRequired = true)]
public string Property2
{
get { return this["Property2"].ToString(); }
set { this["Property2"] = value; }
}
}
}
}
自定义结点3(Node3)的类Test3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration; namespace Config
{
public class Test3:ConfigurationSection
{
[ConfigurationProperty("T1", IsRequired = true)]
public MyTextElement T1
{
get { return (MyTextElement)this["T1"]; }
}
[ConfigurationProperty("T2", IsRequired = true)]
public MyTextElement T2
{
get { return (MyTextElement)this["T2"]; }
}
} public class MyTextElement : ConfigurationElement
{
[ConfigurationProperty("data",IsRequired=true)]
public string CommandText
{
get { return this["data"].ToString(); }
set { this["data"] = value; }
} //这里由我们控制对数据的读写操作,也就是要重载方法SerializeElement,DeserializeElement。
protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey)
{
CommandText = reader.ReadElementContentAs(typeof(string), null) as string;
} protected override bool SerializeElement(System.Xml.XmlWriter writer, bool serializeCollectionKey)
{
if (writer != null)
{
writer.WriteCData(CommandText);
}
return true;
} }
}
自定义结点4(Node4)的类Test4
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration; namespace Config
{
public class Test4:ConfigurationSection
{
private static readonly ConfigurationProperty s_property =
new ConfigurationProperty(string.Empty, typeof(MyKeyValueCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
[ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
public MyKeyValueCollection KeyValues
{
get { return (MyKeyValueCollection)base[s_property]; }
}
} [ConfigurationCollection(typeof(MyKeyValueSetting))]
public class MyKeyValueCollection:ConfigurationElementCollection //自定义一个集合
{
// 基本上,所有的方法都只要简单地调用基类的实现就可以了。
public MyKeyValueCollection()
: base(StringComparer.OrdinalIgnoreCase) //不区分大小写
{ } // 其实关键就是这个索引器。但它也是调用基类的实现,只是做下类型转就行了。
new public MyKeyValueSetting this[string name]
{
get
{
return (MyKeyValueSetting)base.BaseGet(name);
}
}
// 下面二个方法中抽象类中必须要实现的。
protected override ConfigurationElement CreateNewElement()
{
return new MyKeyValueSetting();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MyKeyValueSetting)element).Key;
} // 说明:如果不需要在代码中修改集合,可以不实现Add, Clear, Remove
public void Add(MyKeyValueSetting setting)
{
base.BaseAdd(setting);
}
public void Clear()
{
base.BaseClear();
}
public void Remove(string name)
{
base.BaseRemove(name);
}
} public class MyKeyValueSetting:ConfigurationElement //集合中的每个元素
{
[ConfigurationProperty("key", IsRequired = true)]
public string Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
[ConfigurationProperty("value", IsRequired = true)]
public string Value
{
get { return this["value"].ToString(); }
set { this["value"] = value; }
}
}
}
读取配置信息
//connectionStrings结点验证
private void btnConnectionStrings_Click(object sender, EventArgs e)
{
//需添加System.configuration引用,引用—添加引用—.NET—System.configuration
string connectionStrings = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
if (string.IsNullOrEmpty(connectionStrings))
{
connectionStrings = "没有读到数据!";
}
txbConRead.Text=connectionStrings;
} //AppStrings结点验证
private void btnAppSettings_Click(object sender, EventArgs e)
{
string appSettings = ConfigurationManager.AppSettings["AppString"];
if (string.IsNullOrEmpty(appSettings))
{
appSettings = "没有读到数据!";
}
txbAppRead.Text = appSettings;
}
#region 自定义结点读取 //第一种方式读取自定义结点
private void btnPro1Read_Click(object sender, EventArgs e)
{
Test1 test1 = (Test1)ConfigurationManager.GetSection("Node1");
txbPro11Read.Text = test1.Property1;
txbPro21Read.Text = test1.Property2;
}
//第二种方式读取自定义结点
private void btnPro2Read_Click(object sender, EventArgs e)
{
Test2 test2 = (Test2)ConfigurationManager.GetSection("Node2");
txbPro12Read.Text = test2.Property.Property1;
txbPro22Read.Text = test2.Property.Property2;
} //第三种方式读取自定义结点
private void btnPro3Read_Click(object sender, EventArgs e)
{
Test3 test3 = (Test3)ConfigurationManager.GetSection("Node3");
txbPro13Read.Text = test3.T1.CommandText.Trim();
txbPro23Read.Text = test3.T2.CommandText.Trim();
} //第四种方式读取自定义结点
private void btnPro4Read_Click(object sender, EventArgs e)
{
Test4 test4 = (Test4)ConfigurationManager.GetSection("Node4");
txbtest4Read.Text = string.Join("\r\n", (
from kv in test4.KeyValues.Cast<MyKeyValueSetting>()
let s = string.Format("{0}={1}", kv.Key, kv.Value)
select s).ToArray()
);
}
#endregion
写入配置信息
#region 自定义结点写入
/*
* 在修改配置节点前,我们需要调用ConfigurationManager.OpenExeConfiguration(),然后调用config.GetSection()在得到节点后,
* 转成我们定义的节点类型, 然后就可以按照强类型的方式来修改我们定义的各参数项,最后调用config.Save();即可。
* .net为了优化配置节点的读取操作,会将数据缓存起来,如果希望使用修改后的结果生效,您还需要调用ConfigurationManager.RefreshSection方法。
* 如果是修改web.config,则需要使用 WebConfigurationManager。
*/ //写入connectionStrings结点
private void btnConWrite_Click(object sender, EventArgs e)
{
//ConnectionStringSettings s = new ConnectionStringSettings("ConString1", "server=127.0.0.1;database=DB;uid=sa;pwd=123456");
//ConfigurationManager.ConnectionStrings.Add(s);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["ConString"].ConnectionString = txbConWrite.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
MessageBox.Show("修改成功!");
txbConWrite.Text = "";
} //写入AppStrings结点
private void btnAppWrite_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["AppString"].Value = txbAppWrtite.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
MessageBox.Show("修改成功!");
txbAppWrtite.Text = "";
} //第一种方式写入自定义结点
private void btnPro1Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test1 test1 = config.GetSection("Node1") as Test1;
test1.Property1 = txbPro11Write.Text;
test1.Property2 = txbPro21Write.Text;
config.Save();
ConfigurationManager.RefreshSection("Node1"); //刷新
MessageBox.Show("修改成功!");
txbPro11Write.Text = "";
txbPro21Write.Text = "";
} //第二种方式写入自定义结点
private void btnPro2Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test2 test2 = config.GetSection("Node2") as Test2;
test2.Property.Property1 = txbPro12Write.Text;
test2.Property.Property2 = txbPro22Write.Text;
config.Save();
ConfigurationManager.RefreshSection("Node2");//刷新
MessageBox.Show("修改成功!");
txbPro12Write.Text = "";
txbPro22Write.Text = "";
} //第三种方式写入自定义结点
private void btnPro3Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test3 test3 = config.GetSection("Node3") as Test3;
test3.T1.CommandText = txbPro13Write.Text;
test3.T2.CommandText = txbPro23Write.Text;
config.Save();
ConfigurationManager.RefreshSection("Node3");
MessageBox.Show("修改成功!");
txbPro13Write.Text = "";
txbPro23Write.Text = "";
} //第四种方式写入自定义结点
private void btnPro4Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test4 test4 = config.GetSection("Node4") as Test4;
test4.KeyValues.Clear();
(
from s in txbtest4Write.Lines
let p = s.IndexOf('=')
where p >
select new MyKeyValueSetting { Key = s.Substring(, p), Value = s.Substring(p + ) }
).ToList()
.ForEach(kv => test4.KeyValues.Add(kv));
config.Save();
ConfigurationManager.RefreshSection("Node4");
MessageBox.Show("修改成功!");
txbtest4Write.Text = "";
}
#endregion
完整的读写方法
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Xml; namespace Config
{
public partial class ConfigCheck : Form
{
public ConfigCheck()
{
InitializeComponent();
} //connectionStrings结点验证
private void btnConnectionStrings_Click(object sender, EventArgs e)
{
//需添加System.configuration引用,引用—添加引用—.NET—System.configuration
string connectionStrings = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
if (string.IsNullOrEmpty(connectionStrings))
{
connectionStrings = "没有读到数据!";
}
txbConRead.Text=connectionStrings;
} //AppStrings结点验证
private void btnAppSettings_Click(object sender, EventArgs e)
{
string appSettings = ConfigurationManager.AppSettings["AppString"];
if (string.IsNullOrEmpty(appSettings))
{
appSettings = "没有读到数据!";
}
txbAppRead.Text = appSettings;
}
#region 自定义结点读取 //第一种方式读取自定义结点
private void btnPro1Read_Click(object sender, EventArgs e)
{
Test1 test1 = (Test1)ConfigurationManager.GetSection("Node1");
txbPro11Read.Text = test1.Property1;
txbPro21Read.Text = test1.Property2;
}
//第二种方式读取自定义结点
private void btnPro2Read_Click(object sender, EventArgs e)
{
Test2 test2 = (Test2)ConfigurationManager.GetSection("Node2");
txbPro12Read.Text = test2.Property.Property1;
txbPro22Read.Text = test2.Property.Property2;
} //第三种方式读取自定义结点
private void btnPro3Read_Click(object sender, EventArgs e)
{
Test3 test3 = (Test3)ConfigurationManager.GetSection("Node3");
txbPro13Read.Text = test3.T1.CommandText.Trim();
txbPro23Read.Text = test3.T2.CommandText.Trim();
} //第四种方式读取自定义结点
private void btnPro4Read_Click(object sender, EventArgs e)
{
Test4 test4 = (Test4)ConfigurationManager.GetSection("Node4");
txbtest4Read.Text = string.Join("\r\n", (
from kv in test4.KeyValues.Cast<MyKeyValueSetting>()
let s = string.Format("{0}={1}", kv.Key, kv.Value)
select s).ToArray()
);
}
#endregion #region 自定义结点写入
/*
* 在修改配置节点前,我们需要调用ConfigurationManager.OpenExeConfiguration(),然后调用config.GetSection()在得到节点后,
* 转成我们定义的节点类型, 然后就可以按照强类型的方式来修改我们定义的各参数项,最后调用config.Save();即可。
* .net为了优化配置节点的读取操作,会将数据缓存起来,如果希望使用修改后的结果生效,您还需要调用ConfigurationManager.RefreshSection方法。
* 如果是修改web.config,则需要使用 WebConfigurationManager。
*/ //写入connectionStrings结点
private void btnConWrite_Click(object sender, EventArgs e)
{
//ConnectionStringSettings s = new ConnectionStringSettings("ConString1", "server=127.0.0.1;database=DB;uid=sa;pwd=123456");
//ConfigurationManager.ConnectionStrings.Add(s);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["ConString"].ConnectionString = txbConWrite.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
MessageBox.Show("修改成功!");
txbConWrite.Text = "";
} //写入AppStrings结点
private void btnAppWrite_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["AppString"].Value = txbAppWrtite.Text;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
MessageBox.Show("修改成功!");
txbAppWrtite.Text = "";
} //第一种方式写入自定义结点
private void btnPro1Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test1 test1 = config.GetSection("Node1") as Test1;
test1.Property1 = txbPro11Write.Text;
test1.Property2 = txbPro21Write.Text;
config.Save();
ConfigurationManager.RefreshSection("Node1"); //刷新
MessageBox.Show("修改成功!");
txbPro11Write.Text = "";
txbPro21Write.Text = "";
} //第二种方式写入自定义结点
private void btnPro2Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test2 test2 = config.GetSection("Node2") as Test2;
test2.Property.Property1 = txbPro12Write.Text;
test2.Property.Property2 = txbPro22Write.Text;
config.Save();
ConfigurationManager.RefreshSection("Node2");//刷新
MessageBox.Show("修改成功!");
txbPro12Write.Text = "";
txbPro22Write.Text = "";
} //第三种方式写入自定义结点
private void btnPro3Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test3 test3 = config.GetSection("Node3") as Test3;
test3.T1.CommandText = txbPro13Write.Text;
test3.T2.CommandText = txbPro23Write.Text;
config.Save();
ConfigurationManager.RefreshSection("Node3");
MessageBox.Show("修改成功!");
txbPro13Write.Text = "";
txbPro23Write.Text = "";
} //第四种方式写入自定义结点
private void btnPro4Write_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Test4 test4 = config.GetSection("Node4") as Test4;
test4.KeyValues.Clear();
(
from s in txbtest4Write.Lines
let p = s.IndexOf('=')
where p >
select new MyKeyValueSetting { Key = s.Substring(, p), Value = s.Substring(p + ) }
).ToList()
.ForEach(kv => test4.KeyValues.Add(kv));
config.Save();
ConfigurationManager.RefreshSection("Node4");
MessageBox.Show("修改成功!");
txbtest4Write.Text = "";
}
#endregion }
}
效果图
参考网站:http://www.cnblogs.com/aehyok/p/3558661.html
Config配置文件读写的更多相关文章
- c# Config配置文件读写
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...
- C#读写config配置文件
应用程序配置文件(App.config)是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序. 对于一个config ...
- C# 读写App.config配置文件的方法
我们经常会希望在程序中写入一些配置信息,例如版本号,以及数据库的连接字符串等.你可能知道在WinForm应用程序中可以利用Properties.Settings来进行类似的工作,但这些其实都利用了Ap ...
- C#中动态读写App.config配置文件
转自:http://blog.csdn.net/taoyinzhou/article/details/1906996 app.config 修改后,如果使用cofnigurationManager立即 ...
- C# 读写App.config配置文件
一.C#项目中添加App.config配置文件 在控制台程序中,默认会有一个App.config配置文件,如果不小心删除掉,或者其他程序需要配置文件,可以通过添加得到. 添加步骤:右键项目名称,选择“ ...
- 读写App.config配置文件的方法
我们经常会希望在程序中写入一些配置信息,例如版本号,以及数据库的连接字符串等.你可能知道在WinForm应用程序中可以利用Properties.Settings来进行类似的工作,但这些其实都利用了Ap ...
- Winform—C#读写config配置文件
现在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager.并且AppSettings属性是只读的,并不支持修改属性值. 一.如 ...
- C#读写config配置文件--读取配置文件类
一:通过Key访问Value的方法: //判断App.config配置文件中是否有Key(非null) if (ConfigurationManager.AppSettings.HasKeys()) ...
- .NET平台开源项目速览(1)SharpConfig配置文件读写组件
在.NET平台日常开发中,读取配置文件是一个很常见的需求.以前都是使用System.Configuration.ConfigurationSettings来操作,这个说实话,搞起来比较费劲.不知道大家 ...
随机推荐
- 关于overflow:hidden和bfc
在练习tab选项卡的时候遇到了设置div内部li出现了影响外层相邻div浮动的情况,早就知道overflow:hidden可以清除这种情况产生的浮动,但是为什么它可以清除呢?我们往下看: 首先看一下我 ...
- 初涉JavaScript模式系列 阶段总结及规划
总结 不知不觉写初涉JavaScript模式系列已经半个月了,没想到把一个个小点进行放大,竟然可以发现这么多东西. 期间生怕对JS的理解不到位而误导各位,读了很多书(个人感觉JS是最难的oo语言),也 ...
- 看源码之Adapter和AdapterView之间的关系
总述 Android中"列表"的实现其实一个典型的MVC模式,其实中AdapterView相当于是View,负责视图的绘制以及视图的事件响应,Adapter相当于是Controll ...
- 关于Chrome(谷歌浏览器)对docume,准确获取网页客户区的宽高、滚动条宽高、滚动条Left和Top
对于document.compatMode,很多朋友可能都根我一样很少接触,知道他的存在却不清楚他的用途.今天在ext中看到 document.compatMode的使用,感觉这个对于我们开发兼容性的 ...
- Unix中$$、$@、$#、$*的意思
$$: 表示当前命令进程的PID $#: 表示参数的个数 $@ 和 $* : 都表示输出所有的参数 区别: $*:表示合并为一个参数 “$1 $2 $3 $n” $@:表示分解为多个参数 “$1” ...
- 移动app测试浅析
移动App测试浅析 1. 移动App测试的现状及其挑战 移动互联网走到今天,App寡头化的趋势已经越来越明显,同时用户的口味越来越高,这对移动App开发者提出了更高的要求.几年前可能你有一个创意,随便 ...
- 转:Mongodb中随机的查询文档记录
简述,摘要:在实际应用场景中,几乎都会有随机获取数据记录的需求.而这个需求在Mongodb却不是很好实现,就目前而言,大致上有三种解决方案:1. 先计算出一个从0到记录总数之间的随机数,然后采用ski ...
- 《FPGA零基础入门到精通视频教程》-第001a讲软件的安装
高清视频和配套讲义这里下载 http://www.fpgaw.com/thread-67758-1-1.html 优酷视频不是很清晰
- poj Organize Your Train part II
http://poj.org/problem?id=3007 #include<cstdio> #include<algorithm> #include<cstring& ...
- XML SAX解析
SAX是一种占用内存少且解析速度快的解析器,它采用的是事件驱动,它不需要解析完整个文档,而是按照内容顺序,看文档某个部分是否符合xml语法,如果符合就触发相应的事件.所谓的事件就是些回调方法( cal ...