C# Winform 操作 App.config(新增、修改、刪除、讀取)

  • 3237
  • 0
  • C#
  • 2019-10-16

App config 操作

C# Winform 操作 App.config(新增、修改、刪除、讀取)

操作App config之前要先導入 System.Configuration 及 主檔案 using System.Configuration

app.config 新增item

private void additem(string account,string password)

{

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings.Add(“account”, account);

config.AppSettings.Settings.Add(“password”, password);

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection(“appSettings”);

}

app.config 檢查item是否存在

private bool existkeyname(string keyname)

{

foreach (string key in ConfigurationManager.AppSettings)

{

if(key==name)

{

return true;

}

}

return false;

}

app.config 修改item

private void modifyitem(string account,string password)

{

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings[“account”].Value = account;

config.AppSettings.Settings[“password”].Value = password;

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection(“appSettings”);

}

app.config 刪除item

private void delete(string[] keyname)

{

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

foreach(string key in keyname)

{

config.AppSettings.Settings.Remove(key);

}

config.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection(“appSettings”);

}

app.config 取item值

private string[] getitemvalue(string[] keyname)

{

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

string[] info=new string[keyname.Length];

for (int i = 0; i < keyname.Length;i++ )

{

info[i] = config.AppSettings.Settings[keyname[i]].Value;

}

return info;

}