目录
一、简介
二、添加引用
三、添加节点
1.普通配置节点
2.数据源配置节点
四、管理类 ConfigHelper.cs
1.获取配置节点
2.更新或加入配置节点
结束
在C#中,配置文件很常用,ASP.NET 和 Winform 名称不同,用法一样,如下图
config 文件通常用来存储一些需要修改的数据,比如用户名密码,连接数据库的IP地址等,而不是在代码中写死。有人可能会问,那我自己自定义一个配置文件也行,为什么要用它这个?区别当然有,微软自己封装的读取和写入会更简单一些,你自己封装的,就要自己去封装测试,但最终的效果其实是一样的。
添加 System.Configuration.dll
常用的下面两种,第一种是常用的方式 appSettings,第二种是用在数据库的 connectionStrings
这种写法,读取方式可以用下面的方式
string connStr = ConfigurationManager.AppSettings["url"];
如果是 int 类型,可以直接转换类型
int appYear = int.Parse(ConfigurationManager.AppSettings["app.year"]);
int appMonth = int.Parse(ConfigurationManager.AppSettings["app.month"]);
int appDay = int.Parse(ConfigurationManager.AppSettings["app.day"]);
代码:
using System.Configuration;
namespace Utils
{
public class ConfigHelper
{
///
///返回*.exe.config文件中appSettings配置节的value项
///
///
///
public static string GetAppConfig(string strKey)
{
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == strKey)
{
return config.AppSettings.Settings[strKey].Value.ToString();
}
}
return null;
}
///
///在*.exe.config文件中appSettings配置节增加一对键值对
///
///
///
public static void UpdateAppConfig(string newKey, string newValue)
{
string file = System.Windows.Forms.Application.ExecutablePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(file);
bool exist = false;
foreach (string key in config.AppSettings.Settings.AllKeys)
{
if (key == newKey)
{
exist = true;
}
}
if (exist)
{
config.AppSettings.Settings.Remove(newKey);
}
config.AppSettings.Settings.Add(newKey, newValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
}
}
//获取配置节
string res = ConfigHelper.GetAppConfig("COM1");
Console.WriteLine("====================" + res);
效果:
//更新或加入配置节
ConfigHelper.UpdateAppConfig("COM2", "xxxxxxxx");
运行后,我们需要在配置文件中查看效果是否实现,打开生成目录下的config文件
可以看到,已经自动加入了一个配置节
如果这个帖子对你有用,欢迎关注 + 点赞 + 留言,谢谢
end