config配置:
要在程序中使用自定义配置我们还需要实现存取这个配置块的类型,一般需要做如下三件事:
1. 定义类型从System.Configuration.ConfigurationSection继承
2. 定义配置类的属性,这些属性需要用ConfigurationProperty特性修饰,并制定属性在配置节中的名称和其他一些限制信息
3. 通过基类的string索引器实现属性的get ,set
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; namespace configToRead { public class MySection1 : ConfigurationSection { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("url", IsRequired = true)] public string Url { get { return this["url"].ToString(); } set { this["url"] = value; } } } }
前台代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using configToRead; using System.Configuration; using System.Net.Configuration; using System.Collections.Specialized; namespace configToRead { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MySection1 mySectioin1 = (MySection1)ConfigurationManager.GetSection("MySection111"); textBox1.Text = mySectioin1.UserName; textBox1.Text += mySectioin1.Url; } } }
将App.config包含到项目即可