如何验证ConnectionString是否存在,如果不存在则不抛出错误

时间:2011-07-06 16:03:31

标签: c# connection-string validation

在应用程序配置中找不到连接名称“MySqlServer”,或者连接字符串为空。

所以,我有一个带有面板的页面,当找到web配置中的连接并且连接有效时,该面板将显示;使用try / catch,只要添加名称“VALUE”在配置连接字符串中,如果服务器数据不好,页面将加载并且面板设置为不可见...我需要能够处理以下内容。 ..

如果在这种情况下,在aspx中使用MySqlServer的命名值; aspx.cs但在配置中找不到我不希望发生错误;找不到连接名称....我只是想不显示面板,就像当找到名字时SqlConnection.Open失败但数据不好...

ASPX

   <asp:SqlDataSource runat="server" ID="allowedIPsSqlDataSource" 
    ConnectionString="<%$ ConnectionStrings:MySqlServer %>"

aspx.cs

string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"].ToString();
        SqlConnection SqlConnection = new SqlConnection(connectionString);
        SqlCommand SqlCommand = new SqlCommand();
        try
        {
            SqlConnection.Open();

配置

<connectionStrings>
        <add name="NotMySqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>
<add name="NotMy2SqlServer" providerName="System.Data.SqlClient" connectionString="server=TEST\SQL2005;database=ADB;Integrated Security=True"/>

    </connectionStrings>

3 个答案:

答案 0 :(得分:16)

您可以尝试:

if(ConfigurationManager.ConnectionStrings["MySqlServer"] == null) throw ...

答案 1 :(得分:7)

您可以使用count来检查是否存在任何连接字符串。

var count = ConfigurationManager.ConnectionStrings.Count;
if (count > 0)
{
    //There is at least more then one connection string.
}

更新

public static class Extension
{
    public static bool HasConnectionString(this ConnectionStringSettingsCollection value, string key)
{
    try
    {
        return value[key].ConnectionString.Length > 0;
    }catch 
    {
        return false;
    }
}
}

您可以按照以下方式使用扩展程序。

if (ConfigurationManager.ConnectionStrings.HasConnectionString("MySqlServer"))
{
    //If true you know there is a valid connectionstring.
}

答案 2 :(得分:6)

如果您使用的是.NET 4.5+并且可以访问C#6.0,则可以使用空合并运算符(?)来尝试获取连接字符串,而不会自动抛出异常:

string connectionString = ConfigurationManager.ConnectionStrings["MySqlServer"]?.ConnectionString;
//------------------------------------------------------------------------HERE-^-HERE-------------

if (string.IsNullOrWhiteSpace(connectionString))
{
    // Don't even bother trying to open the connection.
    // Log the error and either rethrow the exception (throw;) or exit from your current context (return;).
    //return;
    //throw;
}

// If your code has made it this far, it means you have a valid connection string.  Now try to use it.
using (var sqlConnection = new SqlConnection(connectionString))
{
    sqlConnection.Open();

    using (var sqlCommand = new SqlCommand)
    {
        // Do stuff.
    }
}