简体   繁体   中英

Cannot access connection string in app.config by using c#

App.config file configuration 1

        <?xml version="1.0" encoding="utf-8" ?>
        <configuration>
          <connectionStrings>
            <add name="MyDBConnectionString" connectionString="Data Source=223.29.207.133;
                 Initial Catalog=MBV5DBLive;User ID=smsuser;Password=sms;IntegratedSecurity=true"
                 providerName="System.Data.SqlClient" />
          </connectionStrings>
        </configuration>

App.config file configuration 2

<configuration>
  <connectionStrings>
    <add name="MyDBConnectionString" connectionString="Data Source=localhost;
         Initial Catalog=University;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>


C# code



 try
                    {
                        String constring = ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;

                        using (SqlConnection con = new SqlConnection(constring))
                        {
                        }
                    }
                    catch (Exception ex)

even if i debug when it comes to configuration manager code will jump to catch block and it will show "Object reference not set to an instance of an object." What is the issue with above both configuration files?

Your connection string name seems like c_str not MyDBConnectionString .

And since you don't have any MyDBConnectionString in your web config, your ConfigurationManager.ConnectionStrings["MyDBConnectionString"] returns null and that's why you get NullReferenceException when you try to access ConnectionString property of a null reference.

If everything is okey other than that, this should work;

var constring = ConfigurationManager.ConnectionStrings["c_str"].ConnectionString;
using (var con = new SqlConnection(constring))
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM