C# 修改Config文件,增删查改

本章讲述:C# 修改Config文件的方法

首先设置路径

private static string configPath = string.Empty;
private static string configName = "TestViewer.exe.config";

public MainWindow()
{
    InitializeComponent();
    configPath = System.Windows.Forms.Application.StartupPath + "\\" + configName;
    GetConfig();
}

获取Configuration方法有两种:

第一种方法:要求exe文件和Config文件在同一个目录下;

Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath );//不需要后缀名

第二种方法:不要求exe文件和Config文件在同一目录下,该方法是制定Config文件的具体路径;

Config文件读取

private void GetConfig()
{
	if(System.IO.File.Exists(configPath))
	{
		ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
		ecf.ExeConfigFilename = configPath;
		Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
		var keys = config.AppSettings.Settings.AllKeys.ToList();
		if (keys == null || keys.Count == 0)
			return;

		if (keys.Contains("SoftVer"))
		{
			SoftVer = config.AppSettings.Settings["SoftVer"].Value.ToString();
		}
	}
	else
	{
		MessageBox.Show("配置文件不存在,请检查!");
	}
}

Config文件保存

private void SaveConfig(string key, string value)
{
	ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
	ecf.ExeConfigFilename = configPath;
	Configuration config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
	if (config.AppSettings.Settings[key] != null)
	{
		config.AppSettings.Settings[key].Value = value;
	}
	else
	{
		config.AppSettings.Settings.Add(key, value);
	}

	config.Save(ConfigurationSaveMode.Modified);
}

文件保存调用代码示例

private void Save()
{
    if (!string.IsNullOrEmpty(SoftVer))
        SaveConfig("SoftVer", SoftVer.ToString());
    ConfigurationManager.RefreshSection("appSettings");
}

Config文件其他操作

private void test()
{
    //增加<add>元素
    config.AppSettings.Settings.Add("VersionType", "V1.5.0.8");
    //删除<add>元素
    config.AppSettings.Settings.Remove("VersionType");
    //保存
    config.Save(ConfigurationSaveMode.Modified);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值