How to use the ConfigurationManager.AppSettings

前端 未结 4 1173
囚心锁ツ
囚心锁ツ 2021-01-30 21:12

I\'ve never used the \"appSettings\" before. How do you configure this in C# to use with a SqlConnection, this is what I use for the \"ConnectionStrings\"

SqlCon         


        
相关标签:
4条回答
  • 2021-01-30 21:20

    ConfigurationManager.AppSettings is actually a property, so you need to use square brackets.

    Overall, here's what you need to do:

    SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
    

    The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.

    0 讨论(0)
  • 2021-01-30 21:31

    \if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

     <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />
    

    In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

     con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
    
    0 讨论(0)
  • 2021-01-30 21:33

    Your web.config file should have this structure:

    <configuration>
        <connectionStrings>
            <add name="MyConnectionString" connectionString="..." />
        </connectionStrings>
    </configuration>
    

    Then, to create a SQL connection using the connection string named MyConnectionString:

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    

    If you'd prefer to keep your connection strings in the AppSettings section of your configuration file, it would look like this:

    <configuration>
        <appSettings>
            <add key="MyConnectionString" value="..." />
        </appSettings>
    </configuration>
    

    And then your SqlConnection constructor would look like this:

    SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);
    
    0 讨论(0)
  • 2021-01-30 21:35

    you should use []

    var x = ConfigurationManager.AppSettings["APIKey"];
    
    0 讨论(0)
提交回复
热议问题