using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Web; namespace iiie.CacheControl.Business.OutputCache { public class FileOuputCache : IOutputCache { private string TempPath { get; set; } public FileOuputCache(string tempPath) { TempPath = tempPath; } public string GetPath(string key) { key = HttpUtility.UrlEncode(key); if (!Directory.Exists(TempPath)) Directory.CreateDirectory(TempPath); return Path.Combine(TempPath, key); } public override object Get(string key) { try { var path = GetPath(key); var formatter = new BinaryFormatter(); var stream = new FileStream(path, FileMode.Open); var obj = formatter.Deserialize(stream); stream.Close(); return obj; } catch (Exception) { return null; } } public override void Remove(string key) { var path = GetPath(key); File.Delete(path); } public override bool Contains(string key) { var path = GetPath(key); return File.Exists(path); } public override void Add(string key, object o) { FileStream stream = null; try { var path = GetPath(key); var formatter = new BinaryFormatter(); stream = new FileStream(path, FileMode.OpenOrCreate); formatter.Serialize(stream, o); stream.Close(); stream = null; } catch (Exception e) { if (stream != null) stream.Close(); Remove(key); } } } }