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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. private string TempPath { get; set; }
  10. public FileOuputCache(string tempPath)
  11. {
  12. TempPath = tempPath;
  13. }
  14. public string GetPath(string key)
  15. {
  16. key = HttpUtility.UrlEncode(key);
  17. if (!Directory.Exists(TempPath))
  18. Directory.CreateDirectory(TempPath);
  19. return Path.Combine(TempPath, key);
  20. }
  21. public override object Get(string key)
  22. {
  23. try
  24. {
  25. var path = GetPath(key);
  26. var formatter = new BinaryFormatter();
  27. var stream = new FileStream(path, FileMode.Open);
  28. var obj = formatter.Deserialize(stream);
  29. stream.Close();
  30. return obj;
  31. }
  32. catch (Exception)
  33. {
  34. return null;
  35. }
  36. }
  37. public override void Remove(string key)
  38. {
  39. var path = GetPath(key);
  40. File.Delete(path);
  41. }
  42. public override bool Contains(string key)
  43. {
  44. var path = GetPath(key);
  45. return File.Exists(path);
  46. }
  47. public override void Add(string key, object o)
  48. {
  49. FileStream stream = null;
  50. try
  51. {
  52. var path = GetPath(key);
  53. var formatter = new BinaryFormatter();
  54. stream = new FileStream(path, FileMode.OpenOrCreate);
  55. formatter.Serialize(stream, o);
  56. stream.Close();
  57. stream = null;
  58. }
  59. catch (Exception e)
  60. {
  61. if (stream != null)
  62. stream.Close();
  63. Remove(key);
  64. }
  65. }
  66. }
  67. }