/// <summary> /// 构造函数。 /// </summary> /// <param name="filePath">文件路径。</param> /// <param name="loadType">加载方式。</param> /// <param name="fileKeyType">缓存键类型。</param> public FileCacheItem(string filePath, DataLoadType loadType, CacheKeyType fileKeyType) { this.FilePath = filePath; if (!File.Exists(this.FilePath)) { throw new ArgumentException(filePath + " 文件不存在!"); } this.FileLoadType = loadType; this.FileKeyType = fileKeyType; this.FileName = Path.GetFileNameWithoutExtension(this.FilePath); this.FileExtension = Path.GetExtension(this.FilePath); this.LastAccessDate = DateTime.Now; this.ItemSize = new FileInfo(this.FilePath).Length; this.ItemKey = this.FilePath; if (this.FileKeyType == CacheKeyType.MD5 || this.FileLoadType == DataLoadType.Load) { using (FileStream fstream = new FileStream(this.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (this.FileKeyType == CacheKeyType.MD5) { this.ItemKey = iPower.Cryptography.HashCrypto.HashFile(fstream, "md5"); fstream.Seek(0, SeekOrigin.Begin); } if (this.FileLoadType == DataLoadType.Load) { using (BufferBlockUtil block = new BufferBlockUtil()) { byte[] buf = new byte[1024]; int len = 0; while ((len = fstream.Read(buf, 0, buf.Length)) > 0) { block.Write(buf, 0, len); } this.FileBytes = block.ToArray(); } } fstream.Close(); } } }
/// <summary> /// 下载文件。 /// </summary> /// <param name="fileName">文件名称。</param> /// <returns>文件数据。</returns> public byte[] Download(string fileName) { if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName", "文件名不能为空!"); byte[] data = null; string path = Path.GetFullPath(this.root + "\\" + fileName); if (File.Exists(path)) { using (BufferBlockUtil block = new BufferBlockUtil()) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { int count = 0; byte[] buffer = new byte[1024]; while ((count = fs.Read(buffer, 0, buffer.Length)) > 0) { block.Write(buffer, 0, count); } fs.Close(); } data = block.ToArray(); } } return data; }
/// <summary> /// 延时加载数据。 /// </summary> internal void DelayLoad() { if ((this.FileBytes == null || this.FileBytes.Length == 0) && (this.FileLoadType == DataLoadType.DelayLoad) && File.Exists(this.FilePath)) { using (FileStream fstream = new FileStream(this.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (BufferBlockUtil block = new BufferBlockUtil()) { byte[] buf = new byte[1024]; int len = 0; while ((len = fstream.Read(buf, 0, buf.Length)) > 0) { block.Write(buf, 0, len); } this.FileBytes = block.ToArray(); } } } }