问题
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".
回答1:
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;
回答2:
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");
}
}
}
}
来源:https://stackoverflow.com/questions/10731482/calling-connection-string-from-app-setings-app-config-file-to-c-sharp-code