您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。