Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;Password=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?

like image 288
Srivastava Avatar asked Nov 23 '10 14:11

Srivastava


People also ask

What information is contained in the app config file?

App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.

How do you declare a variable in CS?

Declaring (Creating) Variablestype variableName = value; Where type is a C# type (such as int or string ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

Is app config and web config are same?

The web. config file is required for ASP.NET webpages. The app. config file is optional in an application and doesn't have to be used when writing desktop applications.

Where are app config files stored?

Windows uses the %APPDATA% directory for user specific application configuration files.


2 Answers

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"]);
like image 111
Serkan Hekimoglu Avatar answered Oct 10 '22 22:10

Serkan Hekimoglu


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);
like image 29
Albireo Avatar answered Oct 10 '22 22:10

Albireo