Is there a standard method for creating a configuration file for a C # program?

In the past, I simply created a text file with key value pairs, for example WIDTH = 40, and manually parsed the file. This becomes a little cumbersome, there is a standard way to do this, preferably with built-in support from Visual Studio or the .NET framework.

+4
source share
3 answers

Configuration files are one of the built-in templates. Right-click on your project, select "Add" - "Create". In the template field, select a configuration file.

+6
source

You can create an application configuration file in Visual Studio. This is basically an XML file that can be used to save application configuration data, but it is not intended to be read as an XML file: the .net framework provides some classes for interacting with it.

This link may provide some background and example code: Using application configuration files in .NET

You can put this code in your .config file:

 <configuration> <appSettings> <add key="SomeData" value="Hello World!" /> </appSettings> </configuration> 

And you can read it this way in C # (reference to the System.Configuration assembly required):

 Console.WriteLine( "Your config data: {0}", ConfigurationManager.AppSettings["SomeData"]); 

Note that you need to avoid entering data into an XML file; for example, & would become &amp;

+4
source

In your C # project, look in the folder: Properties and open the Settings.setting file. Here you can specify settings at the user or application level.

The following code example shows how to use the settings:

 public partial class MyControl : UserControl { MyProject.Properties.Settings config_; public MyControl { InitializeComponent(); config_ = new MyProject.Properties.Settings(); } public void SaveToConfig() { // save to configuration file config_.ReportFileName = dataFileName.Text; config_.Save(); } public void LoadFromConfig() { string dataFileName = config_.ReportFileName; } } 

You can also use the settings at application launch and change your settings when updating the application.

 static void Main() { // if user setting program version user setting is less than MyProject.Properties.Settings config = new MyProject.Properties.Settings(); string version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); if (config.Version != version) { // migrate from version 1.0.2 to future versions here... if (config.Version == null) { } config.Upgrade(); config.Reload(); config.Version = version; config.Save(); } 
+1
source

Source: https://habr.com/ru/post/1299212/


All Articles