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:

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

  2. To read a configuration setting, use the ConfigurationManager.AppSettings property. This property returns a NameValueCollection containing all the key-value pairs from the configuration file.

using System.Configuration;

// Reading a configuration setting
string settingValue = ConfigurationManager.AppSettings["SettingKey"];
  1. To write a configuration setting, use the Configuration class along with the ConfigurationManager.OpenExeConfiguration method to open the configuration file. Then, use the AppSettings.Settings property 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.

  1. Finally, make sure to save the changes using the Configuration.Save method and refresh the section using ConfigurationManager.RefreshSection to reflect the changes immediately.

That's it! You can now read and write configuration settings in your C# WinForms program

read write config file for C# winform program

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

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