开发者

Can we declare variables in the 'app.config' file?

I have a form which needs to get connected to SQL Server, and I have a drop down for selecting the list of databases and perform operations like primary key checking, etc.

But presently my connection string looks like this:

SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Passwor开发者_如何学God=gp");

But apart from the given database, I need to take it variable, so that I can connect it to the database I select from the dropdown.

How can I do this?


Hmm you can declare your variables like this

<appSettings>
    <add key="SmtpServerHost" value="********" />
    <add key="SmtpServerPort" value="25" />
    <add key="SmtpServerUserName" value="******" />
    <add key="SmtpServerPassword" value="*****" />
</appSettings>

and read like

string smtpHost = ConfigurationManager.AppSettings["SmtpServerHost"];
int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpServerHost"]);


I think he wants a "semi constant":

Web.Config

<?xml version='1.0' encoding='utf-8'?>
<configuration>
    <connectionStrings>
        <add name="YourName" providerName="System.Data.ProviderName" connectionString="Data Source={0}; Initial Catalog=myDataBase; User Id=myUsername; Password=myPassword;" />
    </connectionStrings>
</configuration>

CS file

String Servername = "Test";
String ConnectionString = String.Format(ConfigurationManager.ConnectionStrings["YourName"].ConnectionString, ServerName);


you can use the connectionStrings tag in the app.config configuration. You can add as many as you want (giving them each a separate key) and then retrieve them

example app.config xml (set providerName to a valid provider, for example System.Data.SqlClient, and the appropriate connection string) :

<?xml version='1.0' encoding='utf-8'?>
  <configuration>
    <connectionStrings>
      <clear />
      <add name="firstDb" 
       providerName="System.Data.ProviderName" 
       connectionString="Valid Connection String;" />
      <add name="secondDb" 
       providerName="System.Data.ProviderName" 
       connectionString="Valid Connection String;" />
    </connectionStrings>
  </configuration>

example on getting them and listing them (in your case, you would create the appropriate items in the dropdown and set the values) :

ConnectionStringSettingsCollection settings =
            ConfigurationManager.ConnectionStrings;

        if (settings != null)
        {
            foreach(ConnectionStringSettings cs in settings)
            {
                Console.WriteLine(cs.Name);
                Console.WriteLine(cs.ProviderName);
                Console.WriteLine(cs.ConnectionString);
            }
        }


You could use the AppSettings section. Read here for an example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜