Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the past I would just create a text file with key value pairs for example WIDTH=40 and manually parse the file. This is getting a little cumbersome is there a standard way to do this preferably with inbuilt support from Visual Studio or the .NET framework.

like image 283
deltanovember Avatar asked Dec 22 '22 06:12

deltanovember


2 Answers

Configuration files are one of the built-in templates. Right-click on your project, choose Add->New Item. In the template box, select configuration file.

like image 83
Joel Etherton Avatar answered Jan 23 '23 18:01

Joel Etherton


You could to create an Application Configuration File in Visual Studio. It's basically and XML file which you can to use to save your application configuration data, but it's not meant to be read as an XML file: .net framework provides some classes to interact with it.

This link can provide some background and sample code: Using Application Configuration Files in .NET

You could to place this code inside your .config file:

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

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

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

Note you'll need to escape your data ti fit into a XML file; for instance, a & character would became &amp;

like image 22
Rubens Farias Avatar answered Jan 23 '23 18:01

Rubens Farias