从App.config中获取连接字符串

时间:2010-05-11 20:12:25

标签: c# winforms connection-string app-config configurationmanager

我有一个我在C#中开发的Winforms应用程序,它将作为SQL Server 2005数据库的前端。我将可执行文件推送到测试机器并运行它。它在测试机器上运行得非常好,直到我做的最后一轮更改。但是,现在在测试机器上,它会在打开时立即抛出以下异常:

System.NullReferenceException: Object reference not set to an instance of an object.
       at PSRD_Specs_Database_Administrat.mainMenu.mainMenu_Load(Object sender, EventArgs e)
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

我在此版本中更改了与mainMenu_Load相关的唯一内容是调用数据库的连接字符串的方式。以前,我在每个需要调用它的表单上设置了一个带有连接字符串的字符串,如:

string conString = "Data Source = SHAREPOINT;Trusted_Connection = yes;" +
                   "database = CustomerDatabase;connection timeout = 15";

随着我的应用程序的增长,我向其添加了表单,我决定将App.config添加到项目中。我在其中定义了连接字符串:

<connectionStrings>
  <add name="conString"
   providerName="System.Data.SqlClient"
   connectionString="Data Source = SHAREPOINT;Trusted_Connection = yes;database = CustomerDatabase;connection timeout = 15" />
</connectionStrings>

然后我创建了一个返回conString的静态字符串:

public static string GetConnectionString(string conName)
{
    string strReturn = string.Empty;
    if (!(string.IsNullOrEmpty(conName)))
    {
        strReturn = ConfigurationManager.ConnectionStrings[conName].ConnectionString;
    }
    else
    {
        strReturn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    }
    return strReturn;
}

我删除了conString变量,现在调用连接字符串,如下所示:

PublicMethods.GetConnectionString("conString").ToString()

这似乎给了我错误。我更改了这些实例,直接从App.config调用连接字符串,而不使用GetConnectionString。例如,在SQLConnection中:

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString))

这也引发了例外。但是,当我回到每个表单上使用conString变量时,我没有任何问题。我不明白的是为什么这三种方法在我的开发机器上工作正常,而直接使用App.config或通过我创建的静态字符串抛出异常。

1 个答案:

答案 0 :(得分:4)

好的,愚蠢的问题。您确定在测试计算机上将连接字符串添加到app.config吗?你确定拼写正确吗?您确定将connectionStrings部分放在app.config中的正确位置吗?你确定你把app.config放在正确的位置吗?你确定你正确地拼写了“app.config”,而不是app.cfg或app.cofig(我之前发过那个胖子)

相关问题