2012-01-10 35 views
0

我使用app.config文件來存儲和讀取一些參數(sql服務器實例名稱,用戶,密碼,日誌目錄等)。現在,我需要修改一些依賴於用戶的參數,並且只有在我從bin/release目錄運行.exe時才管理它。 當我創建安裝程序並安裝我的應用程序時,我無法更改此參數 - 它會引發TargetInvocationException。我試圖以管理員身份運行我的應用程序,但沒有成功。在運行時修改app.config拋出異常

的代碼,我目前使用的是以下幾點:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings.Remove("username"); 
config.AppSettings.Settings.Add("username", this.Config.Username); 
config.Save(ConfigurationSaveMode.Modified); 
ConfigurationManager.RefreshSection("appSettings"); 

我試過計算器上,但沒有成功發現了一些其他的解決方案......

+0

當你運行代碼,你有什麼值this.Config.Username .. ?? – MethodMan 2012-01-10 17:11:40

+1

這是一個非常經典的UAC陷阱。您可以在開發機器上調試程序時修改該文件,但安裝後無法運行。 'c:\ program files'中的文件是不可寫的。您需要一個單獨的程序來編輯該文件,以便它可以請求UAC提升。或者不使用設置來存儲這些信息,AppData中的.xml文件也可以工作。 – 2012-01-10 18:42:02

+0

用戶名@DJKRAZE的值是有效的。閱讀作品。 – davor 2012-01-10 20:24:07

回答

0

嘗試是這樣的

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
KeyValueConfigurationCollection settings = config.AppSettings.Settings; 
// update SaveBeforeExit 
settings[username].Value = "newkeyvalue"; //how are you getting this.Config.Username 
    ... 
//save the file 
config.Save(ConfigurationSaveMode.Modified); 
//relaod the section you modified 
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); 

這裏有一些步驟要遵循例如,如果我想修改一個基於日期時間值的設置..這個簡單的解釋應該可以讓您輕鬆遵循。

1: // Open App.Config of executable 
2: System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
3: // Add an Application Setting. 
4: config.AppSettings.Settings.Remove("LastDateChecked"); 
5: config.AppSettings.Settings.Add("LastDateChecked", DateTime.Now.ToShortDateString()); 
6: // Save the configuration file. 
7: config.Save(ConfigurationSaveMode.Modified); 
8: // Force a reload of a changed section. 
9: ConfigurationManager.RefreshSection("appSettings"); 
0

理想情況下,我們無法在應用程序運行時修改配置條目。

當您從bin運行exe時,它不會修改* .exe.config。

改爲修改* .vshost.exe.Config文件。

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); returns reference to *.vshost.exe.Config file 

* .exe.config是隻讀的,您無法更新此文件。

相關問題