/// <summary> /// 初始化缓存 /// </summary> public void Initialize() { lock (this) { if (!mRootDirectory.Exists) { mRootDirectory.Create(); if (!mRootDirectory.Exists) { VolleyLog.E("Unable to create cache dir {0}", mRootDirectory.FullName); } return; } //获取已缓存文件并添加到缓存表中 FileInfo[] files = mRootDirectory.GetFiles(); if (files == null) { return; } foreach (FileInfo file in files) { FileStream fs = null; try { fs = file.Open(FileMode.OpenOrCreate); CacheHeader entry = CacheHeader.ReadHeader(fs); entry.Size = fs.Length; PutEntry(entry.Key, entry); } catch (IOException) { if (file != null) { file.Delete(); } } finally { try { if (fs != null) { fs.Close(); } } catch (IOException) { } } } } }
/// <summary> /// 获取缓存数据 /// </summary> public Entry Get(string key) { lock (this) { CacheHeader entry = null; mEntries.TryGetValue(key, out entry); if (entry == null) { return(null); } FileInfo file = GetFileForKey(key); FileStream fs = null; try { fs = file.Open(FileMode.OpenOrCreate); CacheHeader.ReadHeader(fs); byte[] data = StreamToBytes(fs, (int)(fs.Length - fs.Position)); return(entry.ToCacheEntry(data)); } catch (IOException e) { VolleyLog.D("{0}:{1}", file.FullName, e.ToString()); } finally { if (fs != null) { try { fs.Close(); } catch (IOException) { } } } return(null); } }