通用自定义XML配置类

前端之家收集整理的这篇文章主要介绍了通用自定义XML配置类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、用XML文件保存配置信息

<?xml version="1.0"?>
<ModuleSettings>
<Server>127.0.0.1</Server>
<UserName>sa</UserName>
<Password>123458</Password>
<Database>KEYTEC</Database>
</ModuleSettings>

2、XML配置操作类

#region  配置的操作类 ModuleConfig
/// <summary>
/// 配置项的操作类
/// 注意:这里用的是静态方法,所以不需要实例化
/// </summary>
public class ModuleConfig
{
//得到配置项对象实例信息
public static ModuleSettings GetSettings()
{
HttpContext context = HttpContext.Current;
ModuleSettings data = (ModuleSettings)context.Cache["ModuleSetting"];//从缓存取
if (data == null)//缓存里没有
{
XmlSerializer serializer = new XmlSerializer(typeof(ModuleSettings));
try
{
//从文件取
string fileName = HttpContext.Current.Server.MapPath(GetSettingsFile());
FileStream fs = new FileStream(fileName,FileMode.Open);
data = (ModuleSettings)serializer.Deserialize(fs);//反序列化
fs.Close();
context.Cache.Insert("ModuleSetting",data,new CacheDependency(fileName));
}
catch (System.IO.FileNotFoundException)
{
//如果文件不存在,则返回一个空对象
data = new ModuleSettings();
}
}
return data;
}
//保存配置数据
public static void SaveSettings(ModuleSettings data)
{
string fileName = HttpContext.Current.Server.MapPath(GetSettingsFile());
XmlSerializer serializer = new XmlSerializer(typeof(ModuleSettings));
// serialize the object
FileStream fs = new FileStream(fileName,FileMode.Create);
serializer.Serialize(fs,data);
fs.Close();
}
//得到配置文件的路径
private static string GetSettingsFile()
{
HttpContext context = HttpContext.Current;
string filePath = (string)context.Cache["ModuleSettingFile"];//从缓存取
if (filePath == null)//缓存没有
{
filePath = ConfigurationSettings.AppSettings["ModuleSettingFile"];//从web.config得到
context.Cache["ModuleSettingFile"] = filePath;//存入缓存
}
return filePath;
}
}
#endregion

3、配置类的使用方法

(1)保存配置

//保存配置
ModuleSettings setting = new ModuleSettings();
setting.Server = "127.0.0.1";
setting.UserName = "sa";
setting.Password = "123456";
setting.Database = "KEYTEC";
ModuleConfig.SaveSettings(setting);
Response.Write("OK");

(2)读取配置

//读取配置
ModuleSettings setting = ModuleConfig.GetSettings();
string server = setting.Server;
string username = setting.UserName;
string pass = setting.Password;
string db = setting.Database;
Response.Write(server + "," + username + "," + pass + "," + db);
原文链接:https://www.f2er.com/xml/299614.html

猜你在找的XML相关文章