Reading connection string from external config file

前端 未结 4 680
一整个雨季
一整个雨季 2020-12-17 16:46

I have created a console application and an app.config file and Connections.config file. The app.config file has a connectionstring property source pointing to the Connectio

相关标签:
4条回答
  • 2020-12-17 16:50

    Your Connections.config file should be as shown below without the xml header

    <connectionStrings>
      <add name="SQLDBConnecion"
       providerName="System.Data.ProviderName"
       connectionString="" />
    </connectionStrings>
    

    Also for it to correctly locate the file in your console application, please set the Copy to Output Directory to Copy Always or Copy If Newer.

    0 讨论(0)
  • 2020-12-17 16:54

    MSDN says:

    Do not include any additional elements, sections, or attributes.

    You need to remove the XML encoding.

    Edit

    Also, you need to set the properties of your config file to Copy to Output Directory = Copy if newer or Copy always.

    enter image description here

    Edit 2

    To build on what Dave said, you add the clear element to your external file. Your final Connections.config file should look exactly like this:

    <connectionStrings>
      <clear/>
      <add name="Name"
         providerName="System.Data.ProviderName"
         connectionString="Valid Connection String;" />
    </connectionStrings>
    
    0 讨论(0)
  • 2020-12-17 16:58

    That first connection string you are getting is inherited from the machine.config. This is described in the MSDN documentation. http://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.90).aspx

    You can use the Clear tag in your config file to remove inherited connection strings. http://msdn.microsoft.com/en-us/library/ayb15wz8(v=vs.90).aspx

    <connectionStrings>
      <clear/>
      <add name="SQLDBConnecion"
       providerName="System.Data.ProviderName"
       connectionString="" />
    </connectionStrings>
    
    0 讨论(0)
  • 2020-12-17 17:08

    There is a nice article on MSDN: https://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx.

    Quote from the article:

    To store connection strings in an external configuration file, create a separate file that contains only the connectionStrings section. Do not include any additional elements, sections, or attributes. This example shows the syntax for an external configuration file.

    <connectionStrings>
      <add name="Name" 
       providerName="System.Data.ProviderName" 
       connectionString="Valid Connection String;" />
    </connectionStrings>
    

    Hope this helps people who run into this question later.

    0 讨论(0)
提交回复
热议问题