ListFileHandler.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. /// <summary>
  7. /// FileManager 的摘要说明
  8. /// </summary>
  9. public class ListFileManager : Handler
  10. {
  11. enum ResultState
  12. {
  13. Success,
  14. InvalidParam,
  15. AuthorizError,
  16. IOError,
  17. PathNotFound
  18. }
  19. private int Start;
  20. private int Size;
  21. private int Total;
  22. private ResultState State;
  23. private String PathToList;
  24. private String[] FileList;
  25. private String[] SearchExtensions;
  26. public ListFileManager(HttpContext context, string pathToList, string[] searchExtensions)
  27. : base(context)
  28. {
  29. this.SearchExtensions = searchExtensions.Select(x => x.ToLower()).ToArray();
  30. this.PathToList = pathToList;
  31. }
  32. public override void Process()
  33. {
  34. try
  35. {
  36. Start = String.IsNullOrEmpty(Request["start"]) ? 0 : Convert.ToInt32(Request["start"]);
  37. Size = String.IsNullOrEmpty(Request["size"]) ? Config.GetInt("imageManagerListSize") : Convert.ToInt32(Request["size"]);
  38. }
  39. catch (FormatException)
  40. {
  41. State = ResultState.InvalidParam;
  42. WriteResult();
  43. return;
  44. }
  45. var buildingList = new List<String>();
  46. try
  47. {
  48. var localPath = Server.MapPath(PathToList);
  49. buildingList.AddRange(Directory.GetFiles(localPath, "*", SearchOption.AllDirectories)
  50. .Where(x => SearchExtensions.Contains(Path.GetExtension(x).ToLower()))
  51. .Select(x => PathToList + x.Substring(localPath.Length).Replace("\\", "/")));
  52. Total = buildingList.Count;
  53. FileList = buildingList.OrderBy(x => x).Skip(Start).Take(Size).ToArray();
  54. }
  55. catch (UnauthorizedAccessException)
  56. {
  57. State = ResultState.AuthorizError;
  58. }
  59. catch (DirectoryNotFoundException)
  60. {
  61. State = ResultState.PathNotFound;
  62. }
  63. catch (IOException)
  64. {
  65. State = ResultState.IOError;
  66. }
  67. finally
  68. {
  69. WriteResult();
  70. }
  71. }
  72. private void WriteResult()
  73. {
  74. WriteJson(new
  75. {
  76. state = GetStateString(),
  77. list = FileList == null ? null : FileList.Select(x => new { url = x }),
  78. start = Start,
  79. size = Size,
  80. total = Total
  81. });
  82. }
  83. private string GetStateString()
  84. {
  85. switch (State)
  86. {
  87. case ResultState.Success:
  88. return "SUCCESS";
  89. case ResultState.InvalidParam:
  90. return "参数不正确";
  91. case ResultState.PathNotFound:
  92. return "路径不存在";
  93. case ResultState.AuthorizError:
  94. return "文件系统权限不足";
  95. case ResultState.IOError:
  96. return "文件系统读取错误";
  97. }
  98. return "未知错误";
  99. }
  100. }