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:

  1. First, make sure you have added a reference to the System.Configuration assembly in your project.

  2. 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".

  3. 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>
  1. To read a configuration setting, use the ConfigurationManager.AppSettings property and provide the setting key. For example:
string setting1Value = ConfigurationManager.AppSettings["Setting1"];
  1. To write a configuration setting, use the Configuration class to open the configuration file for writing, and then modify the settings using the AppSettings.Settings property. 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

read write config file for C# winform program easy way

原文地址: https://www.cveoy.top/t/topic/ihqd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录