web.config在数据库链接上的运用[转]
没什么用,只是参考xml文件的读取方式![]()
1
public string GetConnectionString()2

{3
return (IsExistKey("appSettings", appSettingsKey)) ? ConfigurationManager.AppSettings[appSettingsKey] : string.Empty;4
} 5

6
private string GetXmlFileName()7

{8
return HttpContext.Current.Server.MapPath("~/Web.config");9
} 10

11
private XmlDocument GetWebConfig()12

{13
XmlDocument xmlDoc = new XmlDocument();14
xmlDoc.Load(GetXmlFileName());15
return xmlDoc;16
} 17

18
public bool IsExistNode(string strNode)19

{20
XmlDocument xmlDoc = GetWebConfig();21
XmlNode xmlNode = xmlDoc.SelectSingleNode(@"/" + strNode); 22

23
// retrieve the appSettings xmlNode 24
xmlNode = xmlDoc.SelectSingleNode("//" + strNode);25
return (xmlNode != null);26
} 27

28
public bool IsExistKey(string strNodeName, string strKey)29

{30
XmlDocument xmlDoc = GetWebConfig();31
bool IsExist = false; 32

33
//在当前所有节点中循环查找34
XmlNodeList topM = xmlDoc.DocumentElement.ChildNodes;35
foreach (XmlElement element in topM)36

{37
//判断是否存在节点38
if (element.Name == strNodeName)39

{40
XmlNodeList node = element.ChildNodes;41
//判断是否存在定义的信息42
if (node.Count > 0)43

{44
//在子节点中循环查找45
foreach (XmlElement el in node)46

{47
//判断Key是否等于所需信息Liumm48
IsExist = (el.Attributes["key"].InnerXml == strKey);49
if (IsExist) break;50
}51
}52
}53
}54
return IsExist;55
} 56

57
public void SetValue(string key, string value)58

{59
XmlDocument xmlDoc = GetWebConfig();60
XmlNode xmlNode = xmlDoc.SelectSingleNode(@"/appSettings"); 61

62
// retrieve the appSettings xmlNode 63
xmlNode = xmlDoc.SelectSingleNode("//appSettings");64
if (xmlNode == null)65

{66
throw new InvalidOperationException("appSettings section not found");67
}68
try69

{70
// XPath select setting "add" element that contains this key 71
XmlElement addElem = (XmlElement)xmlNode.SelectSingleNode("//add[@key='" + key + "']");72
if (addElem != null)73

{74
addElem.SetAttribute("value", value);75
}76
// not found, so we need to add the element, key and value 77
else78

{79
XmlElement entry = xmlDoc.CreateElement("add");80
entry.SetAttribute("key", key);81
entry.SetAttribute("value", value);82
xmlNode.AppendChild(entry);83
}84
//save it 85
try86

{87
XmlTextWriter writer = new XmlTextWriter(GetXmlFileName(), null);88
writer.Formatting = Formatting.Indented;89
xmlDoc.WriteTo(writer);90
writer.Flush();91
writer.Close();92
} 93

94
catch (Exception ex)95

{96
throw new Exception(ex.Message);97
}98
}99
catch (Exception ex)100

{101
throw new InvalidOperationException(ex.Message);102
}103
}104


浙公网安备 33010602011771号