每个环境使用不同的配置

时间:2013-04-15 10:58:37

标签: c# web-config

我的配置看起来像这样,我不知道如何阅读,如果我选择产品或预览,我想获得价值?

<configuration> 

  <environment name="product">
     <connectionString> connection string</connectionString>
     <logPath>C:\*****</logPath>
     <errorLogPath>C:\*****</errorLogPath>
     <ProcessesNumber>5</ProcessesNumber>
      <sendAtOnce>100</sendAtOnce>
     <restInterval>30000</restInterval>
     <stopTime>30000</stopTime>
 </environment>

 <environment name="preview">
    <connectionString> connctionstring </connectionString>
    <logPath>C:\*****</logPath>
    <errorLogPath>C:\*****</errorLogPath>
    <ProcessesNumber>5</ProcessesNumber>
    <sendAtOnce>100</sendAtOnce>
    <restInterval>30000</restInterval>
   <stopTime>30000</stopTime>
 </environment>

</configuration>

如何在调试中阅读此内容?

2 个答案:

答案 0 :(得分:1)

使用LINQ非常简单

这应该可以帮到你

class Configuration
{
    public string connectionString { get; set; }
    public string logPath { get; set; }
    public string errorLogPath { get; set; }
    public int ProcessesNumber { get; set; }
    public int sendAtOnce { get; set; }
    public int restInterval { get; set; }
    public int stopTime { get; set; }
}

static void Main(string[] args)
{
    try
    {
        XDocument doc = XDocument.Load("config.xml");
        string conftype = "product";

        var configuration = (from config in doc.Elements("configuration").Elements("environment")
                             where config.Attribute("name").Value.ToString() == conftype
                             select new Configuration
                             {
                                 connectionString = config.Element("connectionString").Value.ToString(),
                                 logPath = config.Element("logPath").Value.ToString(),
                                 errorLogPath = config.Element("errorLogPath").Value.ToString(),
                                 ProcessesNumber = int.Parse(config.Element("ProcessesNumber").Value.ToString()),
                                 sendAtOnce = int.Parse(config.Element("sendAtOnce").Value.ToString()),
                                 restInterval = int.Parse(config.Element("restInterval").Value.ToString()),
                                 stopTime = int.Parse(config.Element("stopTime").Value.ToString()),
                             }).First();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

答案 1 :(得分:0)

在C#中,我建议您使用Linq to XML。它位于标准的.net框架(3.5)中,它可以帮助您加载XML,并轻松读取它的每个节点和属性。