取值代码:首先添加应用,System.configuration
string serverName = System.Configuration.ConfigurationManager.AppSettings["serverName"];
string serverIp = System.Configuration.ConfigurationManager.AppSettings["serverIp"];
动态修改或者添加信息到配置文件中代码:
private void frmTransfer_FormClosing(object sender, FormClosingEventArgs e)
{
string jobSaveValue = txtSavePath.Text.Trim();
string tempLateValue = txtSaveTempLate.Text.Trim();
SaveConfig(jobSaveValue,tempLateValue);
}
private void SaveConfig(string jobSaveValue,string tempLateValue)
{
string jobSave = "jobSavePath";
string tempLate = "templateSavePath";
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
List<string> keys = new List<string>(config.AppSettings.Settings.AllKeys);
if (keys.Contains(jobSave))
{
config.AppSettings.Settings[jobSave].Value = jobSaveValue;
}
else
{
config.AppSettings.Settings.Add(jobSave , jobSaveValue);
}
if (keys.Contains(tempLate))
{
config.AppSettings.Settings[tempLate].Value = tempLateValue;
}
else
{
config.AppSettings.Settings.Add(tempLate,tempLateValue);
}
config.Save();
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}