2013-04-07 41 views
8

Tôi muốn đọc giá trị app.config, hiển thị nó trong hộp thư, thay đổi giá trị bằng trình soạn thảo văn bản bên ngoài và cuối cùng hiển thị giá trị được cập nhật.Làm cách nào để tải lại/làm mới app.config?

tôi đã cố gắng sử dụng đoạn mã sau:

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"]); 
} 

Nhưng nó không hoạt động. Nó cho thấy giá trị cũ (trước khi thay đổi trong trình soạn thảo văn bản bên ngoài). Bất kỳ đề xuất nào?

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

Trả lời

2

Bạn có thể thử bằng cách sử dụng đoạn mã sau:

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

Đây không phải là một câu trả lời cho câu hỏi cho đến khi nó giải thích những gì các mã không và tại sao nó giải quyết vấn đề của mình. –

9

Nó có thể giúp bạn

cố gắng để lưu lại cấu hình như thế này

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

và sau đó lấy nó như

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

mã của bạn đã hoạt động đối với tôi. cảm ơn! – jned29

+0

Câu lệnh chính ở đây là 'config.AppSettings.SectionInformation.ForceSave = true'. – Tarik

2

này nên tải lại file app.config từ đĩa:

var appSettings = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings; 
MessageBox.Show(appSettings.Settings["TheValue"].Value); 
Các vấn đề liên quan