2011-04-09 65 views
0

在運行時將寫訪問,我需要改變app.config文件我如何使用C#使用C#在運行時

+0

你想同樣的應用程序app.config? – 2011-04-09 12:28:31

回答

2

你需要一個參考System.Configuration添加到您的項目做到這一點。然後,你可以使用這樣的代碼來修改你的可執行程序的app.config:

// Open App.Config of executable 
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
// Add an Application Setting. 
config.AppSettings.Settings.Remove("LastDateFeesChecked"); 
config.AppSettings.Settings.Add("LastDateFeesChecked", DateTime.Now.ToShortDateString()); 
// Save the configuration file. 
config.Save(ConfigurationSaveMode.Modified); 
// Force a reload of a changed section. 
ConfigurationManager.RefreshSection("appSettings"); 

注意:此代碼似乎不會在調試工作。您必須在「發佈模式」中運行代碼才能使其工作。


這是CodeProject上的promising link

1

不知道,但嘗試這個

設定基準來命名空間

using System.Configuration; 
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
AppSettingsSection configSection = config.AppSettings; 

try { 
    if (configSection != null) { 
    if (configSection.IsReadOnly() == false && configSection.SectionInformation.IsLocked == false) { 
     configSection.Settings("KeyName").Value = "NewValue"; 
    config.Save(); 
    } 
    } 
} 
catch (ConfigurationException ex) { 
    MessageBox.Show(ex.Message, "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
} 

CheckHere

0

啊..你不知道。你的問題可能被解釋爲「我不願意寫它」。這個是正常的。應用程序文件夾不被程序或普通用戶編輯。將您的非靜態配置存儲在其他位置(CommonAppData特殊文件夾)。