自定义XML配置文件的操作类(转)
xml配置文件:
<?xml version="1.0"?>
<ModuleSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DataSource>fujian</DataSource>
<Uid>fujian_zyz</Uid>
<Password>fujian_sql_zyz</Password>
<ShowLogin>false</ShowLogin>
</ModuleSettings>
操作类的实现:
using System;
using System.IO;
using System.Web;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
namespace LTPTOOL
{
#region 配置对象模型类
/// <summary>
/// 李天平
/// 2004.3
/// 配置的modul类(注意相关属性的类型与[XmlElement])
/// use:ModuleSettings settings=ModuleConfig.GetSettings();
/// </summary>
public class ModuleSettings
{
private string datasource;
private string uid;
private string password;
private bool showlogin;
[XmlElement]
public string DataSource
{
set{ datasource=value; }
get{ return datasource; }
}
[XmlElement]
public string Uid
{
set{ uid=value; }
get{ return uid; }
}
[XmlElement]
public string Password
{
set{ password=value; }
get{ return password; }
}
[XmlElement]
public bool ShowLogin
{
set{ showlogin=value; }
get{ return showlogin; }
}
}
#endregion
#region 配置的操作类ModuleConfig
/// <summary>
/// 配置的操作类ModuleConfig。
/// </summary>
public class ModuleConfig
{
public static ModuleSettings GetSettings()
{
ModuleSettings data = null;
XmlSerializer serializer = new XmlSerializer(typeof(ModuleSettings));
try
{
string fileName = "db.config";
FileStream fs = new FileStream(fileName, FileMode.Open);
data = (ModuleSettings)serializer.Deserialize(fs);
fs.Close();
}
catch
{
data = new ModuleSettings();
}
return data;
}
public static void SaveSettings(ModuleSettings data)
{
string fileName = "db.config";
XmlSerializer serializer = new XmlSerializer (typeof(ModuleSettings));
// serialize the object
FileStream fs = new FileStream(fileName, FileMode.Create);
serializer.Serialize(fs, data);
fs.Close();
}
#endregion
}
}
得到配置文件的详细信息;
ModuleSettings settings=ModuleConfig.GetSettings();
txtServer.Text=settings.DataSource;
txtUser.Text=settings.Uid;
txtPass.Text=settings.Password;
保存修改:
settings.DataSource=txtServer.Text;
ModuleConfig.SaveSettings(settings);
对于扩展配置也非常方便,只需修改ModuleSettings的对象模型和ModuleConfig.中的文件名就可以用到任何其他配置文件的操作中。