通用自定义XML配置类-创新互联
1、用XML文件保存配置信息
成都服务器托管,创新互联提供包括服务器租用、成都服务器托管、带宽租用、云主机、机柜租用、主机租用托管、CDN网站加速、申请域名等业务的一体化完整服务。电话咨询:13518219792127.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);
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网站名称:通用自定义XML配置类-创新互联
文章网址:http://myzitong.com/article/dpicjs.html