-
Jun 16th, 2021, 11:09 PM
#1
Thread Starter
Fanatic Member
How do I update the Keys in the app.config file at runtime ?
I found some code examples that update the keys in the app.config file when running without error and not updating, why the code does not update, see my code
file app.config
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FormatImage" value="Jpg" />
<add key="LogFile" value="C:\Windows\Log" />
</appSettings>
</configuration>
Code:
private void cmdUpdate_Click(object sender, EventArgs e)
{
EditAppSetting("LogFile", "D:\Office2010");
}
public static void EditAppSetting(string key, string value)
{
try
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
catch (Exception ex)
{
MessageBox.Show("Error update file App.config: " + ex.Message, "Thông báo kiểm tra !", MessageBoxButtons.OK, MessageBoxIcon.Question);
}
}
-
Jun 16th, 2021, 11:56 PM
#2
Re: How do I update the Keys in the app.config file at runtime ?
Ideally, you wouldn't be changing those setting at run time. It would be better to use the Settings page of the project properties and create User-scoped settings. Application-scoped settings and the default values for User-scoped settings are still stored in that same config file, but a different section. Current values for User-scoped settings are stored in a separate config file that is specific to each Windows user. Both Application- and User-scoped settings are accessed via Properties.Settings.Default but, while Application-scoped settings are read-only, User-scoped settings are read/write. Modifying User-scoped settings is just like setting any other property.
If you're determined to stick with that <appSettings> section or you want to modify Application-scoped settings at run time, be aware that only an administrator will likely be able to do so. For an example, check out this CodeBank thread:
https://www.vbforums.com/showthread....-Config-Files)
Unfortunately, I haven't created a C# version of that but the principles are all exactly the same as in VB and the relevant code will be almost identical.
-
Jun 17th, 2021, 02:40 AM
#3
Thread Starter
Fanatic Member
Re: How do I update the Keys in the app.config file at runtime ?
The program has already been saved, I mistyped the path to save the app.config file, thank you for your help
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|