You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileOuputCache.cs 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using System.Web;
  5. namespace iiie.CacheControl.Business.OutputCache
  6. {
  7. public class FileOuputCache : IOutputCache
  8. {
  9. public string TempPath
  10. {
  11. get { return Path.Combine(Path.GetTempPath(), "co-planningCache"); }
  12. }
  13. public string GetPath(string key)
  14. {
  15. key = HttpUtility.UrlEncode(key);
  16. if (!Directory.Exists(TempPath))
  17. Directory.CreateDirectory(TempPath);
  18. return Path.Combine(TempPath, key);
  19. }
  20. public override object Get(string key)
  21. {
  22. try
  23. {
  24. var path = GetPath(key);
  25. var formatter = new BinaryFormatter();
  26. var stream = new FileStream(path, FileMode.Open);
  27. var obj = formatter.Deserialize(stream);
  28. stream.Close();
  29. return obj;
  30. }
  31. catch (Exception)
  32. {
  33. return null;
  34. }
  35. }
  36. public override void Remove(string key)
  37. {
  38. var path = GetPath(key);
  39. File.Delete(path);
  40. }
  41. public override bool Contains(string key)
  42. {
  43. var path = GetPath(key);
  44. return File.Exists(path);
  45. }
  46. public override void Add(string key, object o)
  47. {
  48. FileStream stream = null;
  49. try
  50. {
  51. var path = GetPath(key);
  52. var formatter = new BinaryFormatter();
  53. stream = new FileStream(path, FileMode.OpenOrCreate);
  54. formatter.Serialize(stream, o);
  55. stream.Close();
  56. stream = null;
  57. }
  58. catch (Exception e)
  59. {
  60. if (stream != null)
  61. stream.Close();
  62. Remove(key);
  63. }
  64. }
  65. }
  66. }