您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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);
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。