2013-04-07 13 views
8

Chcę przeczytać wartość app.config, pokazać ją w oknie komunikatu, zmienić wartość za pomocą zewnętrznego edytora tekstu, a na końcu wyświetlić zaktualizowaną wartość.Jak ponownie załadować/odświeżyć plik app.config?

Próbowałem za pomocą następującego kodu:

private void button2_Click(object sender, EventArgs e) 
{ 
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    ConfigurationManager.RefreshSection("appSettings"); 
    ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); 
    MessageBox.Show(ConfigurationManager.AppSettings["TheValue"]); 
} 

Ale to nie działa. Pokazuje starą wartość (przed zmianą w zewnętrznym edytorze tekstu). Jakieś sugestie?

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<appSettings> 
    <add key="TheValue" value="abc"/> 
</appSettings> 
</configuration> 

Odpowiedz

2

Można spróbować użyć następującego kodu:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
KeyValueConfigurationCollection settings = config.AppSettings.Settings;    
// update SaveBeforeExit 
settings["TheValue"].Value = "WXYZ"; 
config.Save(ConfigurationSaveMode.Modified); 

MessageBox.Show(ConfigurationManager.AppSettings["TheValue"]); 
+1

To nie jest odpowiedź na pytanie, dopóki nie wyjaśnia, co robi i dlaczego kod rozwiązuje swoje problemy. –

9

To może pomóc

spróbuj zapisać konfigurację jak ten

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings["KeyName"].Value = "NewValue"; 
config.AppSettings.SectionInformation.ForceSave = true; 
config.Save(ConfigurationSaveMode.Modified); 

a następnie pobrać je tak

ConfigurationManager.RefreshSection("appSettings"); 
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
+0

Twój kod pracował dla mnie. dzięki! – jned29

+0

Kluczową instrukcją tutaj jest 'config.AppSettings.SectionInformation.ForceSave = true'. – Tarik

2

ten powinien przeładować plik app.config z dysku:

var appSettings = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings; 
MessageBox.Show(appSettings.Settings["TheValue"].Value); 
Powiązane problemy