简体   繁体   中英

Reading a connection string from a class library

I am currently struggling to read a connection string from the App.config inside my WinForms application from my Class Library (and Unit Testing).

I added a 'test' entry to the App.config ;

<connectionStrings>
     <add name="MyConnString" connectionString="Test;" />
</connectionStrings>

My TestMethod looks like this;

    [TestMethod]
    public void TestConnection1()
    {
        string connString = "";

        if (ConfigurationManager.ConnectionStrings["MyConnString"] != null)
        {
            connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
        }

        string expected = "Test;";
        string actual = connString;

        Assert.AreEqual(expected, actual);
    }

This, obviously, fails. Actual 's value is empty. What am I doing wrong?

在此处输入图片说明

您还需要在测试项目的配置中添加连接字符串键。

Regarding your comment to DJ Kraze: " @DJ KRAZE, If I put 0 as index, it returns me a connectionstring for SQLExpress "aspnetdb.mdf". If I put 1 as index, I get an exception ( IndexOutOfRangeException ), so obviously my string is not found."

The problem is you forgot the configuration element. For example:

Referenced from MSDN: Storing and Retrieving Connection Strings

<?xml version='1.0' encoding='utf-8'?>
  <configuration>
    <connectionStrings>
      <clear />
      <add name="Name" 
       providerName="System.Data.ProviderName" 
       connectionString="Valid Connection String;" />
    </connectionStrings>
  </configuration>

The machine.config file also contains a <connectionStrings> section, which contains connection strings used by Visual Studio. When retrieving connection strings by provider name from the app.config file in a Windows application, the connection strings in machine.config get loaded first, and then the entries from app.config . Adding clear immediately after the connectionStrings element removes all inherited references from the data structure in memory, so that only the connection strings defined in the local app.config file are considered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM