是否有可能(以及如何)在C#中在运行时将ConnectionString添加到app.config?

时间:2009-12-02 14:15:42

标签: c# connection-string app-config

我有一个控制台应用程序,它将connectionstring作为参数获取。我必须在app.config中设置一个名为'ConnectionString'的ConnectionString,并将给定的参数设置为sql connectionstring。

谢谢答案。在我得到的链接的帮助下:

  

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

2 个答案:

答案 0 :(得分:10)

是的,你绝对可以在运行时添加/修改/删除app.config中的设置。这就是我通常的做法。

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
        }
}

希望这有帮助。

答案 1 :(得分:-6)

忽略了这个答案,然后看到......

是的 - 看看this

这种方法可能就是你所追求的

System.Configuration.ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings("new name", "new string");