ConfigurationManager.AppSettings in returning null

后端 未结 4 1940
猫巷女王i
猫巷女王i 2020-12-16 15:26

I am using ConfigurationManager.AppSettings[myKey] to read a value from the app.config file in my windows application, but the value returned is always null, even though the

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

    i have two project in my solution first i add app.config file in class library project which all instances is call from console application i added these entries in config file in class lib project

    <appSettings> 
    <add key="userName" value="user2" /> 
    <add key="emilsLimit" value="50" /> 
    </appSettings>
    

    it was throwing null exception when i get these in a class in class library project but when i delete app.config from class Library project and added in Console project it works.Cheers

    Note: Class lib project reference is added in console

    0 讨论(0)
  • 2020-12-16 16:25

    I was having the same problem, but when I added an empty string ( + "") on the end it picks up the string in the appsettings

    for example

    string s = ConfigurationManager.AppSettings["myKey"] + "";
    
    0 讨论(0)
  • 2020-12-16 16:31

    Hard to say from what you've provided here:

    1. Check your spelling of the value in myKey
    2. Ensure you are looking at the right app.config - if this call is in a referenced library and you're expecting a value to come from the calling project's app.config, but your library has an app.config for some reason it may be causing your problem.
    0 讨论(0)
  • 2020-12-16 16:33

    One, perhaps easier, alternative is to use a Settings file. This encapsulates the creation and maintenance of App.config values in a designer GUI and generates code for accessing the values.

    To add a Settings file, right click your project in VS and click 'Add -> New Item', select 'Settings file' and give it a meaningful name, e.g. MainSettings.settings. You can then add an item, e.g. Foo, specify whether it is application or user-wide, define it's type and a assign it a value. In your code you can retreive the value by simple writing MainSettings.Default.Foo.

    After compilation, you can change the value by editing the config file. The setting will appear as follows:-

    <applicationSettings>
        <YourNamespace.MainSettings>
            <setting name="Foo" serializeAs="String">
                <value>Bar</value>
            </setting>
        </YourNamespace.MainSettings>
    </applicationSettings>
    
    0 讨论(0)
提交回复
热议问题