3

I'm trying to call a connection string from the app.config file to C# code. This is the app.config code:

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
 <appSettings>

<add key="connectstring" value="Data Source=server111;Initial Catalog=database1;        Integrated Security=False;Persist Security Info=False; User ID=username;Password=password;Encrypt=True; TrustServerCertificate=True; MultipleActiveResultSets=True"/>

 </appSettings>
</configuration>

This is the C# code:

  private SqlConnection connStudent;  
  connStudent = new SqlConnection(ConfigurationManager.AppSettings["connectstring"].ToString());
  connStudent.Open();

The code should be right, but I'm getting a Null Reference Exception, and while debugging the program, connStudent is always null and does not get the connection string . The error is "Object reference not set to an instance of an object".

2
  • I don't think this solves your issue, but I believe the 'value' from app.config is already being returned as a string so there is no need for ToString(). Commented May 24, 2012 at 5:15
  • The C# code you show is not compilable or even valid, so at least provide the full stacktrace of the exception to better figure where it "might" have been raised at. As of now it is most likely that 'connectstring' is not found in your appSettings and thus AppSettings["connectstring"] returns null. So make sure that your app.config file is actually "build into" the output directory, next to your executable, bearing the same name (like "my.exe.config"). Commented May 24, 2012 at 5:20

2 Answers 2

3

if you are using .NET 2.0 or above Use following

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

and then

string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
Sign up to request clarification or add additional context in comments.

3 Comments

Why the limitation on .NET 3.5+? The ConfigurationManager.ConnectionStrings property was available since .NET 2.0.
Still null. Object reference not set to an instance of an object.
Have you added ref to System.Configuration ?
0

your code is fine. check to make sure your copy to output directory property is set to copy always or copy if newer. if that still doesn't work, try to delete temp obj files.

the following test code works fine.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="connectstring" value="Data Source=server111;Initial Catalog=database1;        Integrated Security=False;Persist Security Info=False; User ID=username;Password=password;Encrypt=True; TrustServerCertificate=True; MultipleActiveResultSets=True"/>
  </appSettings>
</configuration>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection connStudent;
                connStudent = new SqlConnection(ConfigurationManager.AppSettings["connectstring"].ToString());
                //connStudent.Open();
                //connStudent.Close();
                Console.WriteLine("ok");
            }
            catch
            {
                Console.WriteLine("error");
            }
        }

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.