none
Get Connection String RRS feed

  • Question

  • hello ,
                I used appconfig file following code
     
                  <appSettings>
          
                           <add key="constring" value="data source=PC2\SQLSERVER;
                                                       initial catalog=alpha; Integrated Security=SSPI"/>
                 </appSettings>


            In dbconnection code like this
              string constr = ConfigurationSettings.AppSettings["constring"].ToString();


        the following error shows:Configuration system failed to initialize

     

    Sunday, July 12, 2009 6:51 AM

Answers

  • Not sure where the error comes from, but why don't you use the designated connctionStrings section for the App.config?

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      
      <connectionStrings>
        <clear />
        <add name="MyConnectionString"
         providerName="System.Data.SqlClient"
         connectionString= "Data Source=myserver;Initial Catalog=Northwind" />
      </connectionStrings>
      
    </configuration>

    and then

                ConnectionStringSettingsCollection css = ConfigurationManager.ConnectionStrings;
                String cs = css["MyConnectionString"].ConnectionString;
                Console.WriteLine(cs);
    
                // or
    
                ConnectionStringSettings css2 = ConfigurationManager.ConnectionStrings["MyConnectionString"];
                Console.WriteLine(css2.ConnectionString);

    More on this here:

    "Connection Strings and Configuration Files (ADO.NET)"
    http://msdn.microsoft.com/en-us/library/ms254494.aspx

    HTH
    //Michael


    This posting is provided "AS IS" with no warranties.
    Monday, July 13, 2009 8:24 AM