chinazdy吧 关注:4贴子:145
  • 0回复贴,共1

c# APP.cinfig 读写

只看楼主收藏回复

步骤为:①生成
① 配置APP.CINFIG
格式为 :
<appSettings>
<add key="database" value="lol"/>
<add key="datatable" value="lol"/>
</appSettings>
以上就为配置的最简单做法
②读取
需要注意的是:当要读取的时候,首先,必须打开配置文件所在的位置,才能读取和使用该字段的值
//找该配置文件所在路径
string file = System.Windows.Forms.Application.ExecutablePath;
//打开配置文件
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
//读取配置文件
textBox1.Text = System.Configuration.ConfigurationManager.AppSettings["database"];
textBox2.Text = System.Configuration.ConfigurationManager.AppSettings["datatable"];
//刷新配置文件
ConfigurationManager.RefreshSection("appSettings");
③写入
写入配置文件同读取,也是要首先打开配置文件所在文件夹才能使用
//找该配置文件所在路径
string file = System.Windows.Forms.Application.ExecutablePath;
//打开配置文件
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
//填写新的数据
config.AppSettings.Settings["database"].Value = textBox1.Text;
config.AppSettings.Settings["datatable"].Value = textBox2.Text;
//最关键的一步,如果不保存,会导致配置文件的值仍为上次的值,即本次更改无效(下次重启时)
config.Save(ConfigurationSaveMode.Modified);
//刷新配置文件
ConfigurationManager.RefreshSection("appSettings");
④保存


IP属地:江苏1楼2017-10-13 17:08回复