Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store/set configuration settings for a C# application?

Tags:

c#

config

I have some values that I want to be able to set, and the application to load them from some kind of file.

The only concept I can think of, is a simple txt file, that might have the following lines:

DatabaseName = "DB1/test"
DatabasePassword = "password"
Development = "true"

but im thinking it should be in some kind of config file? Plus reading a txt file for these values isnt exactly tidy code. It would be nice if i could get the database name by just saying in my application:

 configfile.DatabaseName

Thanks, Paul

like image 915
IAmGroot Avatar asked Dec 10 '22 05:12

IAmGroot


2 Answers

You really should be using the built in Application Settings

You can directly access simple settings using the ConfigurationManager

ConfigurationManager.AppSettings["MySetting"] = "SomeStuff";
var mySetting = ConfigurationManager.AppSettings["MySetting"];

There is also direct access to your Connection Strings using the ConfigurationManager

var conn = ConfigurationManager.ConnectionStrings["DevSqlServer"];

All this is stored in XML files, and by default your *.config files.


To Answer Doomsknight's question from the comments

Configuration settings can be done a number of ways, but by default, they are stored in two places.

Application Level Settings are stored in a configuration file.

For executable programs this file is located in the same directory as the .exe and is named after the assembly, or executable.

Example: MyAssembly.config, Another.Assembly.config

For web applications, the settings are stored in the web.config file (usually) located in the root directory of the web application. These are applied hierarchically and one can be located at each directory level of the Web Application.

Example: MySite\web.config, MySite\SubDirectory\web.config

User Scoped Settings are stored in the user profile

Example: C:\Documents and Settings\USERNAME\Local Settings\Application Data\ApplicationName

Connection Strings are stored in the <connectionStrings></connectionStrings> section in your config file.

<connectionStrings>
  <clear />
  <add name="Name" 
   providerName="System.Data.ProviderName" 
   connectionString="Valid Connection String;" />
</connectionStrings>

These settings can easily be modified directly in the config file, but without writing some code to automatically refresh sections of the config file (which is possible), an application restart is typically needed.

I hope this helps out.

like image 73
Josh Avatar answered Dec 29 '22 10:12

Josh


.NET has a configuration platform built into it. Just add an app.config file to your project and use the ConfigurationManager library to access the values.

like image 28
The Evil Greebo Avatar answered Dec 29 '22 12:12

The Evil Greebo