简体   繁体   中英

ConnectionString null after reading from app.config

I'm programming in C# with VS 2010. I stored my ConnectionString in an app.config - file and read from it, when I want to open the connection to the database. Unfortunately, the connectionstring is always "null", whatever I'm doing. Here is my app.config - file, which I renamed to "options.config".

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="connstring"
     connectionString="Data Source=10.10.10.10;Initial Catalog=testdb;Integrated Security=SSPI"/>
  </connectionStrings>

</configuration>

I also added the reference to the System.configuration - assembly.

Then just reading from config - file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;

namespace Test_Class
{
   public abstract class SQLConnectionString
    {
   static string connectionstring = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;

   public static string ConnectionString 
   {
       get
       {
           return connectionstring;
       }
       }
}
}

When you start a debug session, if you have a file named app.config, it is copied in the BIN\\DEBUG folder and renamed to YourApplication.Exe.Config .

This name is what the ConfigurationManager expects to find in the current application startup path.

If you rename the app.config to something different then this mechanism doesn't work anymore and you can't expect the ConfigurationManager class to find the info about your connection string in a different file (at least not with some additional code tweaking). Probably you have an old copy of this YourApplication.Exe.Config in the BIN\\DEBUG directory. One that has no ConnectionStrings section defined.

I suggest to rename back the file to app.config and let the VS IDE do its works.

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