C#读取配置文件
在程序中读取和更新App.config中的配置信息:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="JcConn" connectionString ="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.60)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User Id=sxeqdb;Password=sxeqdb"/>
</connectionStrings>
<appSettings>
<add key="JbPath" value="D:\quickly\山西地震\地震图片"/>
</appSettings>
</configuration>
1,添加引用System.Configuration;

2,添加using System.Configuration;
3,代码
<span style="font-size:14px;">string connStr = ""; </span><span style="font-size:14px;">ConfigurationManager.RefreshSection("AppSettings"); </span><span style="font-size:14px;">connStr = System.Configuration.ConfiguratonManager.AppSettings["conn"]; </span><span style="font-size:14px;">// 刷新应用程序配置文件的节点,这样会重新从文件读取,用于在程序运行过程中改了配置信息
ConfigurationManager.RefreshSection("AppSettings");</span>
4,key="key",key的值不区分大小写,即conn和CONN、coNN都一样可以读取到。
写配置文件:
// Open App.Config of executable
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// You need to remove the old settings object before you can replace it
if (isModified)
{
config.AppSettings.Settings.Remove(newKey);
}
// Add an Application Setting.
config.AppSettings.Settings.Add(newKey,newValue);
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
有坑:调试运行的时候,保存的结果在xxxx.vshost.exe.Config而不是xxxx.exe.Config(xxxx是程序名称),所以不要以为程序没写对哈。
本文详细介绍了如何使用C#语言在程序中读取和更新App.config中的配置信息,包括添加引用、代码示例以及注意事项。同时提供了配置文件的写法和保存方法,帮助开发者在运行过程中灵活调整配置。

被折叠的 条评论
为什么被折叠?



