To read and write a config file in a C# WinForms program, you can use the ConfigurationManager class from the System.Configuration namespace. Here's an easy way to do it:

  1. Add a reference to the System.Configuration assembly in your project.

  2. Create a new config file by right-clicking on your project in the Solution Explorer, selecting 'Add' -> 'New Item', and choosing 'Application Configuration File'. Name it 'App.config'.

  3. Open the App.config file and add the desired configuration settings using the following format:

<configuration>
  <appSettings>
    <add key='SettingName' value='SettingValue' />
  </appSettings>
</configuration>
  1. In your C# code, you can read the config settings using the ConfigurationManager.AppSettings property, which returns a NameValueCollection object:
using System.Configuration;

...

string settingValue = ConfigurationManager.AppSettings['SettingName'];
  1. To write or update a config setting, you can use the ConfigurationManager.AppSettings.Set method:
using System.Configuration;

...

ConfigurationManager.AppSettings.Set('SettingName', 'NewValue');

Note: ConfigurationManager.AppSettings.Set method only updates the value in memory and not in the actual config file. To persist the changes to the config file, you can call the ConfigurationManager.RefreshSection method:

using System.Configuration;

...

ConfigurationManager.AppSettings.Set('SettingName', 'NewValue');
ConfigurationManager.RefreshSection('appSettings');

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


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

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