0

我正在尝试将连接字符串从 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.  

提前致谢。

4

1 回答 1

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

于 2013-03-26T11:47:51.810 回答