Object reference not set to an instance of an object. - App.config

后端 未结 5 1980
南笙
南笙 2021-01-03 01:05

I receiving the error and in the local window I am seeing for both conSettings and connectionString value of null. I am right to say ConfigurationManager is null and I need

相关标签:
5条回答
  • 2021-01-03 01:46

    you need to read AppSettings key as below ,

    string connectionString = 
          ConfigurationSettings.AppSettings["MyDBConnectionString"];
    

    still you receive empty value, try below steps

    1. Select the App.Config file in the solution explorer
    2. In the property window select Copy to Output Directory to Copy Always.
    3. Now Build the application and try again.

    to access like below you need to add connectionStrings section in app config

      string connectionString = 
          ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString; // error points here
    

    sample app config

    <?xml version="1.0"?>
    <configuration>
      <connectionStrings>
        <add name="MyDBConnectionString" 
        connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data 
                   Source=E:\...\Database1.mdb"/>
      </connectionStrings>
    </configuration>
    
    0 讨论(0)
  • 2021-01-03 01:47

    This:

    string connectionString = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
    

    is your problem.

    You're accessing ConfigurationManager.ConnectionStrings to get to your configuration item, but in the App.Config file you've put it under appSettings which is a different section of the config file than ConnectionStrings

    You could either put your connection string in the relevant ConnectionStrings section of the app.config (accessible with ConfigurationManager.ConnectionStrings, or access it against the appSettings section.

    See:

    http://msdn.microsoft.com/en-us/library/ms254494(v=vs.80).aspx

    For MSDN guidelines on storing connection strings.

    0 讨论(0)
  • 2021-01-03 01:53

    This happened to me in class library with a console app set to run for debugging.

    It is necessary to add the connection to the app.config in the console app, as it will not find it in your library if you're starting it from an outside process.

    0 讨论(0)
  • 2021-01-03 01:55

    Check if you have put the app.config file under your startup project or not. In my case, I just had to put the app.config file under my startup project, and problem was solved.

    0 讨论(0)
  • 2021-01-03 02:05

    I too faced the same problem even after multiple scrutinizing the app.config files and my code for error, but i didn't found any errors in my code. Eventually i found a silly mistake that my compiler had by default taken the application configuration file name as 'app1.config', and when i changed it to 'app.config' every thing just worked fine for me.

    Hope it will help.

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