read write config file for C# winform program
To read and write a configuration file in a C# WinForms program, you can use the ConfigurationManager class. This class is part of the System.Configuration namespace and provides methods to access configuration settings.
Here's an example of how to read and write a configuration file:
-
First, make sure to add a reference to the
System.Configurationassembly in your project. -
To read a configuration setting, use the
ConfigurationManager.AppSettingsproperty. This property returns aNameValueCollectioncontaining all the key-value pairs from the configuration file.
using System.Configuration;
// Reading a configuration setting
string settingValue = ConfigurationManager.AppSettings["SettingKey"];
- To write a configuration setting, use the
Configurationclass along with theConfigurationManager.OpenExeConfigurationmethod to open the configuration file. Then, use theAppSettings.Settingsproperty to access the appSettings section and modify the desired setting.
using System.Configuration;
// Writing a configuration setting
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["SettingKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Note: Replace "SettingKey" with the actual key name from your configuration file.
- Finally, make sure to save the changes using the
Configuration.Savemethod and refresh the section usingConfigurationManager.RefreshSectionto reflect the changes immediately.
That's it! You can now read and write configuration settings in your C# WinForms program
原文地址: https://www.cveoy.top/t/topic/ihp4 著作权归作者所有。请勿转载和采集!