DirectoryService.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. namespace MediaBrowser.Controller.Providers
  8. {
  9. public interface IDirectoryService
  10. {
  11. List<FileSystemInfo> GetFileSystemEntries(string path);
  12. IEnumerable<FileSystemInfo> GetFiles(string path);
  13. IEnumerable<FileSystemInfo> GetFiles(string path, bool clearCache);
  14. FileSystemInfo GetFile(string path);
  15. }
  16. public class DirectoryService : IDirectoryService
  17. {
  18. private readonly ILogger _logger;
  19. private readonly ConcurrentDictionary<string, List<FileSystemInfo>> _cache = new ConcurrentDictionary<string, List<FileSystemInfo>>(StringComparer.OrdinalIgnoreCase);
  20. public DirectoryService(ILogger logger)
  21. {
  22. _logger = logger;
  23. }
  24. public List<FileSystemInfo> GetFileSystemEntries(string path)
  25. {
  26. return GetFileSystemEntries(path, false);
  27. }
  28. private List<FileSystemInfo> GetFileSystemEntries(string path, bool clearCache)
  29. {
  30. List<FileSystemInfo> entries;
  31. if (clearCache)
  32. {
  33. List<FileSystemInfo> removed;
  34. _cache.TryRemove(path, out removed);
  35. }
  36. if (!_cache.TryGetValue(path, out entries))
  37. {
  38. //_logger.Debug("Getting files for " + path);
  39. try
  40. {
  41. entries = new DirectoryInfo(path).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly).ToList();
  42. }
  43. catch (DirectoryNotFoundException)
  44. {
  45. entries = new List<FileSystemInfo>();
  46. }
  47. _cache.TryAdd(path, entries);
  48. }
  49. return entries;
  50. }
  51. public IEnumerable<FileSystemInfo> GetFiles(string path)
  52. {
  53. return GetFiles(path, false);
  54. }
  55. public IEnumerable<FileSystemInfo> GetFiles(string path, bool clearCache)
  56. {
  57. return GetFileSystemEntries(path, clearCache).Where(i => (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory);
  58. }
  59. public FileSystemInfo GetFile(string path)
  60. {
  61. var directory = Path.GetDirectoryName(path);
  62. var filename = Path.GetFileName(path);
  63. return GetFiles(directory).FirstOrDefault(i => string.Equals(i.Name, filename, StringComparison.OrdinalIgnoreCase));
  64. }
  65. }
  66. }