访问App.Config连接字符串时的TypeInitializationException

时间:2013-06-17 10:01:45

标签: c# connection-string app-config

我创建了一个静态实用程序类来简化对db的访问,并在运行我的代码“TypeInitializationException”时收到以下异常。

<connectionStrings>
  <add name="vistConnectionString" connectionString="XXXXX"/>
</connectionStrings>


static class DBUtility
{
    private static string dbConnection = ConfigurationManager.ConnectionStrings["vistConnectionString"].ConnectionString;

    public static string DbConnection
    {
        get { return dbConnection; }
    }  
}

如果我调用静态属性,那么我会收到一个TypeInitializationException异常

string s = DBUtility.DbConnection; // this line throws the exception

来自例外的消息是

Message=The type initializer for 'VIServiceToolServiceLibrary.Database.DBUtility' threw an exception.

1 个答案:

答案 0 :(得分:0)

使用以下代码进行连接

var connectionString = ConfigurationManager.ConnectionStrings["vistConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
try { con.Open(); }