开发者

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

I have some values that I wan开发者_C百科t 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


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.


.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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜