C#:读取配置文件

时间:2023-07-21 13:47:28

以下代码演示如何读取配置文件
---------------------Factory.cs----------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;//必须引入此程序集

namespace AllTest
{
    public class Factory
    {
        //简单工厂
        public static Animal CreateObject() {
             //关键代码
            String animal = ConfigurationManager.AppSettings["Animal"];
            if (animal.Equals("Dog"))
            {
                return new Dog("日本", "白色");
            }
            else {
                return new Cat("中国","红色");
            }
        }
    }
}

系统配置文件,如下:
------------------------App.config-----------------------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Animal" value="Cat"/>    
  </appSettings>
</configuration>