是的,可以在C#中在运行时将ConnectionString添加到app.config。以下是一种方法:
using System.Configuration;
public static void AddConnectionString(string connectionStringName, string connectionString)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection connectionStringsSection = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (connectionStringsSection != null)
{
ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(connectionStringName, connectionString);
connectionStringsSection.ConnectionStrings.Add(connectionStringSettings);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
AddConnectionString("MyConnectionString", "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=True");
这样,在运行时,就可以将ConnectionString添加到app.config文件中。
需要注意的是,在添加ConnectionString时,需要确保已经添加了对System.Configuration的引用,并且在代码中使用了System.Configuration命名空间。
领取专属 10元无门槛券
手把手带您无忧上云