如何将connectionString从一个配置文件附加到其他配置文件

时间:2013-03-26 11:41:19

标签: c#

我正在尝试将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.  

提前致谢。

1 个答案:

答案 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.");

}

来源:http://msdn.microsoft.com/en-us/library/vstudio/system.configuration.connectionstringsettingscollection.add(v=vs.100).aspx