Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible (and how) to add ConnectionString to app.config at runtime in C#?

I have a console application which gets the connectionstring as a parameter. I would have to set a ConnectionString in app.config with name 'ConnectionString' and the given parameter as the sql connectionstring.

Thx to answers. With help of the links I got to this:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var connectionStringSettings = new ConnectionStringSettings("ConnectionString", _arguments["connectionString"], "System.Data.SqlClient"); config.ConnectionStrings.ConnectionStrings.Add(connectionStringSettings); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings");

like image 333
Lieven Cardoen Avatar asked Dec 02 '09 14:12

Lieven Cardoen


People also ask

How do you read ConnectionString from configuration file into code behind?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].


1 Answers

Yes, you can definitely add/modify/remove settings in the app.config at runtime. This is how I usually do it.

using System.Configuration; // don't forget to add the system.configuration dll to your references.

    public static void CreateConnectionString(string datasource, string initialCatalog, string userId, string password)
    {
        try
        {
            //Integrated security will be off if either UserID or Password is supplied
            var integratedSecurity = string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(password);

            //Create the connection string using the connection builder
            var connectionBuilder = new SqlConnectionStringBuilder
            {
                DataSource = datasource,
                InitialCatalog = initialCatalog,
                UserID = userId,
                Password = password,
                IntegratedSecurity = integratedSecurity
            };

            //Open the app.config for modification
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //Retreive connection string setting
            var connectionString = config.ConnectionStrings.ConnectionStrings["ConnectionStringName"];
            if (connectionString == null)
            {
                //Create connection string if it doesn't exist
                config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings
                {
                    Name = ConnectionName,
                    ConnectionString = connectionBuilder.ConnectionString,
                    ProviderName = "System.Data.SqlClient" //Depends on the provider, this is for SQL Server
                });
            }
            else
            {
                //Only modify the connection string if it does exist
                connectionString.ConnectionString = connectionBuilder.ConnectionString;
            }

            //Save changes in the app.config
            config.Save(ConfigurationSaveMode.Modified);
        }
        catch (Exception)
        {
            //TODO: Handle exception
        }
}

Hope this helps.

like image 186
cubski Avatar answered Oct 23 '22 04:10

cubski