2013-03-26 88 views
0

我試圖將connectionStrings從C:\ test2 \ web.config複製到c:\ test1 \ app.config。在web.config中,connectionString元素如下所示。這兩個配置文件都不屬於我的項目。 如何將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

可以使用的FileReader以及或XML閱讀器。只是一個想法。 – 2013-03-26 11:44:52

回答

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