簡體   English   中英

app.config修改值c#

[英]app.config modify value c#

這里提出的問題是App.Config的變化值

接受的答案是

string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);          
string configFile = System.IO.Path.Combine(appPath, "App.config");

ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();         
configFileMap.ExeConfigFilename = configFile;          

System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["YourThing"].Value = "New Value"; 
config.Save(); 

但是當我試圖實現同樣的東西時,我發現了一種奇怪的行為。 上面的答案在設置值時拋出NullReferenceException config.AppSettings.Settings計數為零。

所以我將configFile路徑設置為項目中的app.config路徑

string configFile = @"D:\App\Schedule\Schedule\App.config";

這會修改項目中的app.config以及bin / debug中的<< appname >> .exe.config。 但我不認為這是一個可行的解決方案,因為應用程序可以部署在任何路徑上。 所以對configPath進行硬編碼是行不通的。

然后我再次修改了給定的configFile

string configFile = System.IO.Path.Combine(appPath, "<appname>.exe.config");

上面的代碼只運行並修改了<< appname >> .exe.config而不是項目中的app.config。

我真的不確定哪個是正確的,或者我遺漏了任何東西。

我在VS 2012,c#4.5,它是控制台應用程序。 截至目前,我的控制台中沒有其他代碼,app.config是

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <appSettings>
        <add key="YourThing" value="" />
    </appSettings>
</configuration>

這只是對app.config的錯誤理解。 您希望應用程序修改您的源代碼是不正確的。

運行程序時,它會創建app.config的副本到bin / debug或bin / release文件夾。

你的第二個解決方案很好。 應用程序按預期工作。

Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            config.AppSettings.Settings["PresentationFolder"].Value = path;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

其中:path - 是“new value”,“appSettings” - 是App.config中的Section

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM