Calling Connection string from App setings app.config file to C# code

匆匆过客 提交于 2020-01-04 05:23:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!