web.config中的ADD和DELETE部分

时间:2014-04-23 19:22:18

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

我要求编辑/删除或添加到web.config的部分 我希望能够在我的web.config文件中添加或删除 connectionStrings 部分

这是我的web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
   </system.webServer>
<connectionStrings />
</configuration>

我使用以下代码添加 connectionStrings

部分
 Dim doc As XmlDocument = New XmlDocument()
 Dim path As String = Server.MapPath("~/Web.Config")
 doc.Load(path)
 Dim newElem As XmlElement = doc.CreateElement("connectionStrings")
 doc.DocumentElement.AppendChild(newElem)
 doc.PreserveWhitespace = False
 Dim wrtr As XmlTextWriter = New XmlTextWriter(path, Encoding.Unicode)
 doc.WriteTo(wrtr)
 wrtr.Close()

我试图操纵代码删除 connectionStrings 部分,但我无法做到。我使用了RemoveChild()函数而不是AppendChild(),但我得到了像

这样的错误
Error 1 Value of type 'String' cannot be converted to 'System.Xml.XmlNode'. 

Object reference not set to an instance of an object.

您可以帮助我使用我的代码删除 connectionStrings 部分吗?

3 个答案:

答案 0 :(得分:0)

要删除connectionstrings节点,请转到父节点(在本例中为configuration),然后使用RemoveChild()功能。这与AppendChild()函数相反。您需要传入要删除的元素。

答案 1 :(得分:0)

Dim doc As XmlDocument = New XmlDocument()
Dim path As String = Server.MapPath("~/Web.Config")
doc.Load(path)
Dim connNode As XmlNode = doc.SelectSingleNode("//connectionStrings")
Dim myparent As XmlNode = connNode.ParentNode
myparent.RemoveChild(connNode)
doc.PreserveWhitespace = False
Dim wrtr As XmlTextWriter = New XmlTextWriter(path,Encoding.Unicode)
doc.WriteTo(wrtr)
wrtr.Close()

答案 2 :(得分:0)

您使用的是WebConfigurationManager&#39;类直接从web.config中删除特定的键。 请参阅以下代码段以删除“连接”#39;字符串

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("connectionstring");
config.Save();
相关问题