现在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager。并且AppSettings属性是只读的,并不支持修改属性值。
1.首先添加引用-System.configguration
2.引用命名空间
3.config配置文件配置节点
常用的分为三种:普通配置节点,数据源配置节点以及自定义配置节点;
1>.普通配置节点:
2>.数据源配置节点:
3>.自定义配置节点:
实际应用:
1.获取配置节点的值:
button1 点击获取配置节
button2 点击获取配置节
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//获取配置节点指定key的value值
textBox1.Text = ConfigurationManager.AppSettings["key1"];
}
private void button2_Click(object sender, EventArgs e)
{
//点击获取配置节点指定name的connectionString值
textBox2.Text = ConfigurationManager.ConnectionStrings["sqlDB"].ToString();
}
}
}
效果预览:
2.修改配置节点的值
获取值按钮 点击获取配置节
修改文本按钮 点击修改配置节
获取修改后值按钮 点击获取配置节
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//获取配置节点指定key的value值
textBox1.Text = ConfigurationManager.AppSettings["key1"];
}
private void button2_Click(object sender, EventArgs e)
{
//修改配置节点指定key的value值为文本框的值
ConfigurationManager.AppSettings.Set("key1", textBox2.Text);
}
private void button3_Click(object sender, EventArgs e)
{
//获取配置节点指定key新的value值
textBox3.Text = ConfigurationManager.AppSettings["key1"];
}
}
}
效果预览:
1.首先同样是添加引用:
Web.config里的配置节点:
1>.读取
string filepath = ConfigurationManager.AppSettings["FilePath"];
2>.添加
//WebConfigManager是web.config所在的文件夹名
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebConfigManager");
AppSettingsSection app = config.AppSettings;
app.Settings.Add("AA", "D:\\");
config.Save(ConfigurationSaveMode.Modified);
3>.修改
//WebConfigManager是web.config所在的文件夹名
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebConfigManager");
AppSettingsSection app = config.AppSettings;
app.Settings["AA"].Value = @"D:\";
config.Save(ConfigurationSaveMode.Modified);
4>.删除
//WebConfigManager是web.config所在的文件夹名
Configuration config = WebConfigurationManager.OpenWebConfiguration("/WebConfigManager");
AppSettingsSection app = config.AppSettings;
app.Settings.Remove("AA");
config.Save(ConfigurationSaveMode.Modified);