【问题标题】:Edit the Web.Config file编辑 Web.Config 文件
【发布时间】:2011-08-18 04:26:34
【问题描述】:

我正在尝试在安装过程中从代码更新 web.config 文件中的一些值。

到目前为止,我已经找到了用于更新连接字符串的方法,

    ' Open Application's Web.Config
    Dim config = WebConfigurationManager.OpenWebConfiguration("/" + TargetVDir, friendlySiteName)

    'Add new connection string setting for web.config
    Dim appDatabase = New ConnectionStringSettings()
    appDatabase.Name = "TimeOffEntities"
    appDatabase.ConnectionString = EFconnectionstring

    config.ConnectionStrings.ConnectionStrings.Clear()
    config.ConnectionStrings.ConnectionStrings.Add(appDatabase)

    ' Persist web.config settings
    config.Save()

但是我需要更新另一个部分,但我不确定如何更新。我有电子邮件的设置,但我不知道如何更新它们。下面的相关web.config部分,

<configuration>

  <system.net>
    <mailSettings>
      <smtp>
        <network 
             host="relayServerHostname" 
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

</configuration>

【问题讨论】:

    标签: .net asp.net vb.net web-config


    【解决方案1】:

    您需要推出自己的一些 XML 解析。或者更好的是,如果您使用 .NET 4,请使用 config file transforms

    【讨论】:

    • 废话,我真的希望如果他们费心制作一个 WebConfigurationManager 类,它能够做到这一点。转换看起来很简单,但我必须弄清楚如何在安装过程中应用它们。
    【解决方案2】:

    你可以这样做:

    Configuration config = WebConfigurationManager.OpenWebConfiguration(...);
    
    ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");
    System.Net.Configuration.SmtpSection smtpSection = section as
                          System.Net.Configuration.SmtpSection;
    if (smtpSection != null)
    {
        smtpSection.Network.Host = ...;
    }
    config.Save();
    

    当然对于其他配置部分也是如此。

    如果您单击the MSDN documentation for the ConfigurationSection class 的继承层次结构部分中的“更多...”,您将获得所有标准配置部分的 ConfigurationSection 派生类型的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-20
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2012-10-24
      • 2012-10-10
      相关资源
      最近更新 更多