通用自定义XML配置类-成都快上网建站

通用自定义XML配置类

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

创新互联建站是一家专注于网站建设、做网站与策划设计,平阴网站建设哪家好?创新互联建站做网站,专注于网站建设十载,网设计领域的专业建站公司;建站业务涵盖:平阴等地区。平阴做网站价格咨询:13518219792



127.0.0.1
sa
123458
KEYTEC

2、XML配置操作类

#region  配置的操作类 ModuleConfig
/// 
/// 配置项的操作类
/// 注意:这里用的是静态方法,所以不需要实例化
/// 
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);

本文标题:通用自定义XML配置类
分享网址:http://kswjz.com/article/jspjds.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流