Getting configuration settings from web.config/app.config using class library

后端 未结 4 1345
春和景丽
春和景丽 2020-12-09 18:48

Configuration settings in 3.5 is driving me nuts... Help! ;)

I have a class library (Named ADI), that needs some configuration settings from the project using it (li

相关标签:
4条回答
  • 2020-12-09 18:59

    Add reference System.web; add name space and user

    using System.Web.Configuration;    
    
    String webConfigValue;
                webConfigValue = WebConfigurationManager.AppSettings["employeeDB"].ToString();
    

    to read the web config value

    <appSettings>
            <add key="employeeDB" value="Data Source=servername;Initial Catalog=employee;Persist Security Info=True;User ID=userid;Password=password;"/>        
    </appSettings>
    
    0 讨论(0)
  • 2020-12-09 19:07

    For ApplicationSettings you should use:

    [YourNamespace].Properties.Settings.Default.[YourSettingName]
    

    This provides a strongly typed reference to your setting and returns the default value if one is not defined in the web.config file. For AppSettings you should use:

    System.Web.Configuration.WebConfigurationManager.AppSettings
    
    0 讨论(0)
  • 2020-12-09 19:16

    If you're not after structured settings, the appSettings section just takes key-value pairs:

    <appSettings>
      <add key="ADIImageRoot" value="C:\DataTemp\ADI\Original\" />
      <add key="ADIImageVariantsRoot" value="C:\DataTemp\ADI\Variants\" />
    </appSettings>
    

    This will enable you to access them via the AppSettings dictionary:

    ConfigurationManager.AppSettings["ADIImageVariantsRoot"]
    

    As you would expect.

    Alternatively, if you need more structure to your configuration (i.e. more than just strings, or a collection of settings), you can look into using a configuration section of your own, using a ConfigurationSection, and its relevant parts.

    0 讨论(0)
  • 2020-12-09 19:16

    You seem to be using the Settings stuff built into visual studio. This generates a wrapper class related to the file, called, in your case MySettings.

    You can thus write something like MySettings.Instance.ADIImageVariantsRoot. (If you click show all files in the project toolbox, it will show you the .settings.cs file and you can see all the gory details)

    0 讨论(0)
提交回复
热议问题