標籤:
常見.NET功能代碼匯總
23,擷取和設定分級緩衝
擷取緩衝:首先從本機快取擷取,如果沒有,再去讀取分布式緩衝
寫緩衝:同時寫本機快取和分布式緩衝
private static T GetGradeCache<T>(string key) where T:struct { MemoryCacheManager localCache = MemoryCacheManager.Instance; if (!localCache.IsSet(key)) { //本地不存在此緩衝 T remoteValue = MemCacheManager.Instance.Get<T>(key); if (!ValueType.Equals(remoteValue, default(T))) { //如果遠程有 localCache.Set(key, remoteValue, 1); } else { localCache.SetFromSeconds(key, default(T), 10); } return remoteValue; } T value = localCache.Get<T>(key); return value; } private static void SetGradeCache<T>(string key,T Value,int time) where T : struct { MemoryCacheManager localCache = MemoryCacheManager.Instance; localCache.Remove(key); localCache.Set(key, Value, time); MemCacheManager.Instance.Remove(key); MemCacheManager.Instance.Set(key, Value, time); }24,求相對目錄的絕對路徑
有時候,我們需要求相對於當前根目錄的相對目錄,比如將記錄檔儲存在網站目錄之外,我們可以使用 ../logs/ 的方式:
string vfileName = string.Format("../logs/{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd")); string rootPath = HttpContext.Current.Server.MapPath("/"); string targetPath = System.IO.Path.Combine(rootPath, vfileName); string fileName = System.IO.Path.GetFullPath(targetPath); string fileDir = System.IO.Path.GetDirectoryName(fileName); if (!System.IO.Directory.Exists(fileDir)) System.IO.Directory.CreateDirectory(fileDir);
這個代碼會在網站目錄之外的日誌目錄,建立一個 代機器名稱的按照日期區分的記錄檔。
25,多次嘗試寫記錄檔方法
記錄檔可能會並發的寫入,此時可能會提示“檔案被另外一個進程佔用”,因此可以多次嘗試寫入。下面的方法會遞迴的進行檔案寫入嘗試,如果嘗試次數用完才會最終報錯。
/// <summary> /// 儲存記錄檔 /// </summary> /// <param name="logFileName">不帶副檔名檔案名稱</param> /// <param name="logText">日誌內容</param> /// <param name="tryCount">如果出錯的嘗試次數,建議不大於100,如果是0則不嘗試</param> public static void SaveLog(string logFileName, string logText, int tryCount) { string vfileName = string.Format("..\\logs\\{0}_{1}_{2}.log", logFileName, System.Environment.MachineName, DateTime.Now.ToString("yyyyMMdd")); string rootPath = System.AppDomain.CurrentDomain.BaseDirectory; string targetPath = System.IO.Path.Combine(rootPath, vfileName); string fileName = System.IO.Path.GetFullPath(targetPath); string fileDir = System.IO.Path.GetDirectoryName(fileName); if (!System.IO.Directory.Exists(fileDir)) System.IO.Directory.CreateDirectory(fileDir); try { System.IO.File.AppendAllText(fileName, logText); tryCount = 0; } catch (Exception ex) { if (tryCount > 0) { System.Threading.Thread.Sleep(1000); logText = logText + "\r\nSaveLog,try again times =" + tryCount + " ,Error:" + ex.Message; tryCount--; SaveLog(logFileName, logText, tryCount); } else { throw new Exception("Save log file Error,try count more times!"); } } }
常見.NET功能代碼匯總 (2)