Fetching connection string from appconfig file in c#

前端 未结 10 886
隐瞒了意图╮
隐瞒了意图╮ 2020-12-19 07:39

I have the following connection string declared in my app.config file:

  
    

        
相关标签:
10条回答
  • 2020-12-19 08:10

    First, you must add the appSettings tag

     <connectionStrings>
        <appSettings>
          <add name="SqlConnectionString" connectionString="Data Source=xxx.xx.xx.xx;Initial Catalog=xxxxx;User Id=xx;Password=xxx;" providerName="System.Data.SqlClient" />
        </appSettings>
      </connectionStrings>
    

    Second, add a reference to System.Configuration to your project and insert a using System.Configuration in the source.

    Then, you can use ConfigurationManager.AppSettings to access your config setting:

    string result = ConfigurationSettings.AppSettings["SqlConnectionString"];
    
    0 讨论(0)
  • 2020-12-19 08:10

    One thing I've noticed when compiling WinForm App in VS 2013:

    I add connection strings my Settings File - which updates my app.config file

    When I would expect:

    var connectionString = ConfigurationManager.ConnectionStrings["theConnectionStringName"].ConnectionString;
    

    I have to write:

    var connectionString = ConfigurationManager.ConnectionStrings["MyAppNameSpace.Properties.Settings.theConnectionStringName"].ConnectionString;
    

    Everything else is business as usual

    0 讨论(0)
  • 2020-12-19 08:12

    Same problem. Based on Merlyn Morgan-Graham and Edward Zhu comments, I rebuilt my project, which used the app.config to create a myapp.exe.config file with the connection string. Original first syntax then worked.

    Other problem: Tried using the project properties dialog to modify the connection string and it added "project.My.Mysettings. to the connection string name. Which caused failure.

    0 讨论(0)
  • 2020-12-19 08:17
    <configuration>
      <appSettings>
       <add key="ConnectionString" value="blah blah blah"/>  </appSettings>
      </configuration>
    

    Will the above configuration works with the API/code like:

    string str = ConfigurationSettings.AppSettings["SqlConnectionString"];
    
    0 讨论(0)
提交回复
热议问题