如何在winforms中将外部app.config读取为xml文件?

时间:2014-01-29 05:35:48

标签: c# xml winforms

如何将app.config文件作为普通xml读取并读取connectionString键/值

来自配置 - > connectionStrings节点

<?xml version="1.0"?>
  <configuration>
    <connectionStrings>
       <add name="appConnStr" connectionString="Data Source=DEV6-PC;Initial Catalog=ireg.est;Persist Security Info=True;User ID=sa;Password=sa@123" providerName=".NET Framework Data Provider for SQL Server"/>
    </connectionStrings>
  <configuration>

2 个答案:

答案 0 :(得分:2)

var element = XDocument.Load("filepath")
                       .Descendants("connectionStrings")
                       .FirstOrDefault();
var connStrings = new Dictionary<string,string>();
if(element != null)
{
   foreach(var item in element.Elements("add"))
   {
      var name = (string)item.Attribute("name");
      var connString = (string)item.Attribute("connectionString");
      connStrings.Add(name,connString);
  }
}

答案 1 :(得分:1)

试试这个:这里我将文件作为xml文档读取并检索连接字符串属性。

string connString=null;
XmlDocument xmldoc = new XmlDocument();
xmldoc.load("yourconfigfielpath"); // add your file path here.
XmlNodeList nodeList = xmlDoc.SelectNodes("/xml/configuration/connectionstrings");
foreach (XmlNode node in nodeList)
{
         connString=node["add"].GetAttribute("connectionString");
}
希望这会有所帮助。