C# App.config学习篇

C# App.config学习篇

说明一下,APP.CONFIG文件如果设置在类库中时,当编译之后,应用程序无法识别,解决方法很简单:修改命名空间。

 

进入公司一年多来,对配置文件添加了不少参数,但是从未想过这些参数是如何被读取出来的,今天把读取参数的处理看了一下,收获不少。假定有App.config如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="family" type="FirstRowTest.Configuration.Settings,FirstRowTest"/>
  </configSections>
<family>
  <familymember>
    <member status="father"
            birth="1954"
            name="AA"
            hobby="reading books">
    </member>
    <member status="mother"
            birth="1958"
            name="BB"
            hobby="chatting">
    </member>
    <member status="elder brother"
            birth="1982"
            name="CC"
            hobby="money">
    </member>
    <member status="younger brother"
            birth="1986"
            name="DD"
            hobby="computer">
    </member>
  </familymember>
</family>
  <appSettings>
    <add key="address" value="maling"/>
  </appSettings>
</configuration>

构造:

    public class Param:System.Configuration.ConfigurationElement
    {
        [System.Configuration.ConfigurationProperty("status")]
        public string Status
        {
            get
            {
                return this["status"] as string;
            }
            set
            {
                this["status"] = value;
            }
        }
        [System.Configuration.ConfigurationProperty("birth")]
        public string Birth
        {
            get
            {
                return this["birth"] as string;
            }
            set
            {
                this["birth"] = value;
            }
        }
        [System.Configuration.ConfigurationProperty("name")]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
            set
            {
                this["name"] = value;
            }
        }
        [System.Configuration.ConfigurationProperty("hobby")]
        public string Hobby
        {
            get
            {
                return this["hobby"] as string;
            }
            set
            {
                this["hobby"] = value;
            }
        }
    }

    public class Params:System.Configuration.ConfigurationElementCollection
    {
        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Param();
        }
        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            Param param = element as Param;
            return param.Status;
        }
        protected override string ElementName
        {
            get
            {
                return "member";
            }
        }
        public override System.Configuration.ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return System.Configuration.ConfigurationElementCollectionType.BasicMap;
            }
        }

    }

    public class Settings:System.Configuration.ConfigurationSection
    {
        [System.Configuration.ConfigurationProperty("familymember")]
        public Params FamilyMember
        {
            get
            {
                return this["familymember"] as Params;
            }
            set
            {
                this["familymember"] = value;
            }
        }
    }

调用:

        public FrmMain()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            //Settings setting = cfg.GetSection("family") as Settings;
            Settings setting = System.Configuration.ConfigurationManager.GetSection("family") as Settings;
            Param first = null;
            if (null != setting)
            {
                foreach (Param p in setting.FamilyMember)
                {
                    if (null == first)
                    {
                        first = p;
                    }
                    this.richTextBox1.AppendText(string.Format("status:{0}|birth:{1}|name:{2}|hobby:{3}\r\n",

                                                                p.Status, p.Birth, p.Name, p.Hobby));
                }
            }
            //cfg.Save();
            System.Configuration.ConfigurationManager.RefreshSection("family");
        }
    }

如果需要进行保存,则处理上有一点变动:

    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            Settings setting = cfg.GetSection("family") as Settings;
            //Settings setting = System.Configuration.ConfigurationManager.GetSection("family") as Settings;
            Param first = null;
            if (null != setting)
            {
                foreach (Param p in setting.FamilyMember)
                {
                    if (null == first)
                    {
                        first = p;
                    }
                    this.richTextBox1.AppendText(string.Format("status:{0}|birth:{1}|name:{2}|hobby:{3}\r\n",

                                                                p.Status, p.Birth, p.Name, p.Hobby));
                }
            }

            first.Name = "I dont know";
            cfg.Save();
            //System.Configuration.ConfigurationManager.RefreshSection("family");
        }

保存结果:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="family" type="FirstRowTest.Configuration.Settings,FirstRowTest"/>
  </configSections>
<family>
  <familymember>
    <member status="father" birth="1954" name="I dont know" hobby="reading books" />
    <member status="mother" birth="1958" name="BB" hobby="chatting" />
    <member status="elder brother" birth="1982" name="CC" hobby="money" />
    <member status="younger brother" birth="1986" name="DD" hobby="computer" />
  </familymember>
</family>
  <appSettings>
    <add key="address" value="maling"/>
  </appSettings>
</configuration>

 

 

今天发现点问题..会出现"给定编码中的字符无效"等情况....

初次加载

pathTemp = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;

.因为我偷油,copy的以前的一个form在修改.懒得重写.在我"打开MyApp.Set"时, 会pathTemp 报错,于是我吧pathTemp 放在方法体内生成.

解决办法:删除 读取的方法,直接打开文件夹修改.config , 甚至直接重写myapp.config就可以.不需要删除.哈哈.

===================== 一般myapp的操作

//打开myapp所在文件夹
        private void button9_Click(object sender, EventArgs e)
        {
            pathTemp = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
            if (Directory.Exists(pathTemp.Substring(0, pathTemp.Length - 12)))
                System.Diagnostics.Process.Start("explorer.exe", pathTemp.Substring(0, pathTemp.Length - 12));
            else
                Directory.CreateDirectory(pathTemp.Substring(0, pathTemp.Length - 12));
        }

  //删除MyApp.Setting
        private void button7_Click(object sender, EventArgs e)
        {
            pathTemp = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
            File.Delete(pathTemp);
        }

   //打开MyApp.Setting      //这里逻辑有点问题.出错就在这里....我也懒得想了.毕竟用的多不在这里..  出现空白的配置文档就是因为这里找不到  而重新File.Create(pathTemp);

--------
        private void button6_Click(object sender, EventArgs e)
        {
            pathTemp = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
            if (Directory.Exists(pathTemp))
                System.Diagnostics.Process.Start("notepad", pathTemp);
            else                 {
                Directory.CreateDirectory(pathTemp.Substring(0, pathTemp.Length - 12));
                File.Create(pathTemp);
            }
        }

----------------------

//MDB和MDF变更重写 MyApp.Setting
        private void button3_Click(object sender, EventArgs e)
        {

            //返回SpiderResult.MDB最大Count ,并保存
            oleConn = new OleDbConnection(Ole_MDB_ConnectionString);
            oleConn.Open();
            MaxNum = Convert.ToInt32(new OleDbCommand("select Count(*) from content", oleConn).ExecuteScalar());
            oleConn.Close();
            WebLink_MDB表个数 = new OtherMethod().Access返回表总数(Ole_MDB_ConnectionString2);
            MyApp.Default.MDB所有数据量 = MaxNum;
            MyApp.Default.MDBTableCount = WebLink_MDB表个数;
            MyApp.Default.MDB发布开始时间 = DateTime.Now.GetDateTimeFormats('d')[0].ToString();
            MyApp.Default.MDB发布数据总量 = 1;
            MyApp.Default.MDB文章下一条 = 1;
            MyApp.Default.发送成功 = 0;
            MyApp.Default.发送失败 = 0;
            MyApp.Default.下一用户名 = 0;
            MyApp.Default.txt_Baidu_ID = "txt_Baidu_ID";
            MyApp.Default.txt_Content = "txt_Content";
            MyApp.Default.txt_Long_Tags = "txt_Long_Tags";
            MyApp.Default.Save();
            if (WebLink_MDB表个数 < Insert文章链接数)
            {
                Insert文章链接数 = WebLink_MDB表个数;
            }
        }

-----------------

=====================================

对于自定义类添加.总是有点纠结的位置.帖出来.方便以后能够找到问题

            if (MyApp.Default.发布报告集 == null)
            {
                MyApp.Default.发布报告集 = new postReportList();
                MyApp.Default.发布报告集.list = new List<postReportObj>();
            }
            MyApp.Default.发布报告集.list.Add(new postReport.postReportObj { StartTime = "1", EndTime = "2", PostOkNum = "3", PostFailNum = "4", PostName = "5" });
            MyApp.Default.Save();

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值