编辑Web.Config文件

时间:2011-08-18 04:26:35

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

我正在尝试在安装过程中从代码更新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>

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您可以按照以下方式执行此操作:

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();

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

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