動態修改配置文件


web配置文件

public class ConfigurationOperator : IDisposable
{
private Configuration config;
public ConfigurationOperator()
:
this(HttpContext.Current.Request.ApplicationPath)
{ }
public ConfigurationOperator(string path)
{
config
= WebConfigurationManager.OpenWebConfiguration(path);
}
/// <summary>
/// 設置應用程序配置節點,如果存在則修改,否則添加此節點
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void SetAppSetting(string key, string value)
{
AppSettingsSection appSetting
= (AppSettingsSection)config.GetSection("appSettings");
if (appSetting.Settings[key] == null)
{
appSetting.Settings.Add(key, value);
}
else
{
appSetting.Settings[key].Value
= value;
}
}
/// <summary>
/// 設置數據庫連接字符串節點
/// </summary>
/// <param name="key"></param>
/// <param name="connectionString"></param>
public void SetConnectionString(string key, string connectionString)
{
ConnectionStringsSection connectionSetting
= (ConnectionStringsSection)config.GetSection("connectionStrings");
if (connectionSetting.ConnectionStrings[key] == null)
{
ConnectionStringSettings connectionStringSettings
= new ConnectionStringSettings(key, connectionString);
connectionSetting.ConnectionStrings.Add(connectionStringSettings);
}
else
{
connectionSetting.ConnectionStrings[key].ConnectionString
= connectionString;
}
}
public void Save()
{
config.Save();
config
= null;
}
public void Dispose()
{
if (config != null)
{
config.Save();
}
}
}

 

 

應用程序配置文件

  private void SaveUserID(string newUser)
{
Configuration config
= ConfigurationManager.OpenExeConfiguration(System.IO.Path.GetFileName(Application.ExecutablePath));
string value = config.AppSettings.Settings["UserId"].Value = newUser;
config.Save();
}

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: