Search code examples
vb.netvisual-studio-2010configurationmanager

vs 2010 reading configuration settings


Coding in VB.net in VS 2010. I have:

Imports System.Configuration and I added a reference to System.Configuration.

When

**MsgBox(ConfigurationManager.AppSettings("sDBName").ToString)**

is executed, it fails, with "Object reference not set to an instance of an object." sDBName is set.

What have I missed?


In response:

Sorry for the delay in getting back to you; other things demanded my attention.

There is no such section in my app.config file. I added sDBName and other settings via the Settings1.settings file; these objects automatically show up in app.cong as follows:

<applicationSettings>
    <QuickRequest.Settings1>
        <setting name="sDBName" serializeAs="String">
            <value>xxx</value>
        </setting>
        <setting name="sInputPath" serializeAs="String">
            <value>c:\yyy\Infile\</value>
        </setting>
     </QuickRequest.Settings1>


Solution

  • You reference settings in VB slightly differently than you do in C#. The easiest way is to use the settings that are part of the project and then reference it through the My namespace:

    MessageBox.Show(My.Settings.sDBName)
    

    (Note, you don't need the .ToString here because sDBName is already a string).

    Since you are including a separate Settings file, you should be able to access its values by calling the Default method to get the instance and then your property off of the default:

    MessageBox.Show(Settings1.Default.sDBName)