版權聲明:本文為博主原創文章,遵循 CC 4.0 by-sa 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/BYH371256/article/details/90236288
本章講述: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);
}
————————————————
版權聲明:本文為CSDN博主「Kaivin.bao」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/BYH371256/article/details/90236288