Calling the connection string from app.config application settings in C # code

I am trying to call a connection string from app.config file in 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 get a Null Reference Exception and when debugging a program, connStudent is always null and does not get a connection string. Error: "The object reference is not installed on the object instance."

+3
c # xml app-config
source share
2 answers

if you are using .NET 2.0 or higher. Use the following

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

and then

 string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; 
+3
source share

your code is ok. make sure your copy to output directory property is set to copy always or copy if newer . if this still does not work, try deleting the temp obj files.

The following test code is working 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"); } } } } 
0
source share

All Articles