我正在尝试将connectionStrings从C:\ test2 \ web.config复制到c:\ test1 \ app.config。在web.config中,connectionString元素如下所示。两个配置文件都不属于我的项目。
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"c:\test1\app.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
ExeConfigurationFileMap fileMapWeb = new ExeConfigurationFileMap();
fileMapWeb.ExeConfigFilename = @"C:\test2\web.config";
Configuration configWeb = ConfigurationManager.OpenMappedExeConfiguration(fileMapWeb, ConfigurationUserLevel.None);
var connectionStringsWeb = (ConnectionStringsSection)configWeb.GetSection("connectionStrings");
//here I got connectionString element in connectionStringsWeb from web.config file. But how to append this connectionString element to app.config file.
提前致谢。
答案 0 :(得分:0)
您可以从代码访问配置文件。
msdn的例子
// Add a connection string to the connection
// strings section and store it in the
// configuration file.
static void AddConnectionStrings()
{
// Get the count of the connection strings.
int connStrCnt =
ConfigurationManager.ConnectionStrings.Count;
// Define the string name.
string csName = "ConnStr" +
connStrCnt.ToString();
// Get the configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Add the connection string.
ConnectionStringsSection csSection =
config.ConnectionStrings;
csSection.ConnectionStrings.Add(
new ConnectionStringSettings(csName,
"LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" +
"Initial Catalog=aspnetdb", "System.Data.SqlClient"));
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
Console.WriteLine("Connection string added.");
}