您的位置:首页 > 编程语言

.NET编程 -- .NET 2.0 中对配置文件的读写

2008-02-20 11:14 441 查看
在基于 .net 2.0 的企业库中,原来的配置应用程序块被废除了,使用了 .net 2.0 自带的读写配置功能,下面我们就来看看 .net 2.0 中读写配置的功能。

即: ConfigurationManager 类

注意:

ConfigurationManager 是处理客户端应用程序配置文件的首选方法;不推荐使用任何其他方法。

对于 Web 应用程序,建议使用 WebConfigurationManager 类。

这个类的 AppSettings 属性 在以前1.0 的时候,就有了, 2.0 中增加了 ConnectionStrings 属性。

这些都不是今天我们要探讨的内容,我们今天要探讨的内容,是把一个配置类保存到配置文件中,以及把这个配置类从配置文件中实例化出来。

这个配置类,必须是 派生自

System.Configuration.ConfigurationSection 类

如下面的类就是一个配置类

using System.Text;

using System.Configuration;

namespace ConfigTest

{

class ConfigDataClass : ConfigurationSection

{

public ConfigDataClass()

{ }

[ConfigurationProperty("id")]

public int ID{

get{return (int)this["id"];}

set{ this["id"] = value;}

}

[ConfigurationProperty("name")]

public string Name{

get{ return this["name"].ToString();}

set{ this["name"] = value;}

}

public override string ToString(){

StringBuilder info = new StringBuilder();

info.AppendFormat("id = {0};name = {1}", ID, Name);

return info.ToString();

}

}

}

先说如何把这个配置类更新到配置文件中

// 配置信息类初始化

ConfigDataClass configData = new ConfigDataClass();

configData.ID = 100;

configData.Name = "我是谁?";

// 打开当前文件的配置文件

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

// 干掉原先的配置

config.Sections.Remove("SettingsData");

// 把新的配置更新上去

config.Sections.Add("SettingsData", configData);

// 保存配置文件

config.Save();

MessageBox.Show(configData.ToString());

读取配置信息

ConfigDataClass configData = ConfigurationManager.GetSection("SettingsData") as ConfigDataClass;

if (configData == null) return;

MessageBox.Show(configData.ToString());

当文件修改的时候,自动从新登录配置文件需求

这个更简单,只需要使用一个 System.IO.FileSystemWatcher 对象即可

private FileSystemWatcher watcher;

在初始化的时候,订阅文件改变事件。

// Initialize file system watcher

watcher = new FileSystemWatcher(AppDomain.CurrentDomain.BaseDirectory);

watcher.Changed += new FileSystemEventHandler(watcher_Changed);

watcher.EnableRaisingEvents = false;

然后在 watcher_Changed 方法中,

private void watcher_Changed(object sender, FileSystemEventArgs e)

{

if (e.FullPath.ToLower().Contains(".config"))

{

for (int i = 0; i < 3; i++)

{

try

{

// Using the static method, read the cached configuration settings

ConfigurationManager.RefreshSection("EditorSettings");

break;

}

catch (ConfigurationErrorsException)

{

if (i == 2) throw;

else Thread.Sleep(100);

}

}

}

}

显然,上述的功能已经能满足我们的需求了,所以企业库才废弃了之前的配置管理应用程序块。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: