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");
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With