ConfigurationManager keeps getting Machine.config connection string

删除回忆录丶 提交于 2019-12-18 04:08:23

问题


I have a c# assembly that uses the app.config to store its database connection string. When debugging the application I noticed that the connection to the database kept failing because the ConfigurationManager kept returning the machine.config connection string:

data source=.\SQLEXPRESS; Integrated Security;....

I added <clear/> before my connection string in the app.config and it fixed the issue on my dev machine. The problem returned when I deployed it to production. Can someone tell me how I can stop the machine.config connection string from being used?

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);

<connectionStrings>
    <clear/>
    <add name="VersionConnectionString"
     connectionString=" Data Source=localhost;Initial Catalog=VersionInfo;User ID=user;Password=password"         
     providerName="System.Data.SqlClient" />
  </connectionStrings>

UPDATE

The following still gives me the machine.config connection string?!

 Configuration appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                string dllConfigData =
                    appConfig.ConnectionStrings.ConnectionStrings[0].ConnectionString;

回答1:


When using connection strings in a DLL, you need to add them to your exe's app.config as well, using the exact same name for the setting. Then, you can change the connection string in the exe's .config file and the DLL will pick it up automatically when loaded.

This is probably the only way you can have working custom connection strings in the app.config file when your DB persistence layer is implemented in a separate DLL. Don't even ask me how much time it took me to research and debug this.




回答2:


I know this is an older question, but I was having the same problem today. The problem was that the app.config that I added to my project wasn't being copied to the output directory. To fix this, right click on the app.config and select Properties. Then change Build Action to Content. Hope this helps!




回答3:


Try getting an instance of your app.config file as a Configuration object:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

var myConnString = config.ConnectionStrings["VersionConnectionString"].ConnectionString;

This bypasses the machine config file completely.




回答4:


You should be getting your connection string by NAME instead of INDEX - that will ensure you're getting what you're asking for.

Try

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["VersionConnectionString"].ConnectionString);


来源:https://stackoverflow.com/questions/3781928/configurationmanager-keeps-getting-machine-config-connection-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!