开发者

What's the best way to get data from the app.config?

For a long time I used:

ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString

to get the connection string from the app.config file

<configuration>
   <connectionStrings>
       <add name="sqlconnectionstring" connectionString="Data  Source=ggg;Initial Catalog =DB;User ID=sa;Password=sa" />
   </connectionStrings>
</configuration>

Lately I found that I canget the string using

global::myProj.Properties.Settings.Default.sqlconnectionstring;
  1. What is the difference?
  2. Can I access a key under appSetting?
  3. How come I don't need to imp开发者_Python百科ort System.Configuration?

Thanks Asaf


The global::myProj.Properties.Settings.Default.sqlconnectionstring; stuff is generated by the settings designer in Visual Studio.

The settings can be found in the solution explorer under Properties->Settings.settings, typesafe wrapper methods are automatically generated for all your properties defined in the settings designer.

This only works for settings defined in the settings designer (connection strings are automatically added to the settings designer).

Edit, to answer your specific questions

  1. The second is a generated wrapper of the first one.
  2. Nope, but if you create your own settings in the settings designer they are stored in another section called "applicationSettings".
  3. The import (or rather used by fully qualified name is done in the generated wrapper class).


I think that your mentioned type global::myProj.Properties.Settings.Default is generated for you by Visual Studio, if you are using a setting for your project. It uses low level infrastructure to gain access to the app.config.

Note that the namespace System.Configuration is available even when you don't reference the System.configuration.dll. It's because several types of the System.Configuration namespace reside in several other assemblies (e.g System.dll), which are referenced by default.

ConfigurationManager resides in the System.configuration.dll. Thus if you want to use it, you'll need to reference that assembly.

If you need access the appSetting section in the app.config file, I think you need to stick to the ConfigurationManager. If you are starting a new application I would recommend using Visual Studio's support for settings and access your settings via the types provided in the global::myProj.Properties namespace.


using global:: is only really required when you need to distinguish between namespaces for a particular method or variable. Further information can be found here

For C# it is far easier to use Properties.Settings.Default to access properties in your config file.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜