read write config file for C# winform program easy way
To read and write a configuration file in a C# WinForms program, you can use the ConfigurationManager class from the System.Configuration namespace. Here's a step-by-step guide:
-
First, make sure you have added a reference to the
System.Configurationassembly in your project. -
Create a new configuration file for your application. You can do this by right-clicking on your project in the Solution Explorer, selecting "Add" > "New Item", and choosing "Application Configuration File". Name the file as "App.config".
-
Open the "App.config" file and define your configuration settings using the following XML structure:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Setting1" value="Value1" />
<add key="Setting2" value="Value2" />
</appSettings>
</configuration>
- To read a configuration setting, use the
ConfigurationManager.AppSettingsproperty and provide the setting key. For example:
string setting1Value = ConfigurationManager.AppSettings["Setting1"];
- To write a configuration setting, use the
Configurationclass to open the configuration file for writing, and then modify the settings using theAppSettings.Settingsproperty. Finally, save the changes. Here's an example:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Setting1"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Make sure to replace "Setting1" with your actual setting key.
That's it! You can now easily read and write settings in your WinForms application's configuration file
原文地址: https://www.cveoy.top/t/topic/ihqd 著作权归作者所有。请勿转载和采集!