DirectoryService.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Collections.Concurrent;
  2. using MediaBrowser.Model.Logging;
  3. using System;
  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<FileInfo> GetFiles(string path);
  13. IEnumerable<DirectoryInfo> GetDirectories(string path);
  14. FileInfo GetFile(string path);
  15. DirectoryInfo GetDirectory(string path);
  16. }
  17. public class DirectoryService : IDirectoryService
  18. {
  19. private readonly ILogger _logger;
  20. private readonly ConcurrentDictionary<string, List<FileSystemInfo>> _cache = new ConcurrentDictionary<string, List<FileSystemInfo>>(StringComparer.OrdinalIgnoreCase);
  21. public DirectoryService(ILogger logger)
  22. {
  23. _logger = logger;
  24. }
  25. public List<FileSystemInfo> GetFileSystemEntries(string path)
  26. {
  27. List<FileSystemInfo> entries;
  28. if (!_cache.TryGetValue(path, out entries))
  29. {
  30. //_logger.Debug("Getting files for " + path);
  31. try
  32. {
  33. entries = new DirectoryInfo(path).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly).ToList();
  34. }
  35. catch (DirectoryNotFoundException)
  36. {
  37. entries = new List<FileSystemInfo>();
  38. }
  39. _cache.TryAdd(path, entries);
  40. }
  41. return entries;
  42. }
  43. public IEnumerable<FileInfo> GetFiles(string path)
  44. {
  45. return GetFileSystemEntries(path).OfType<FileInfo>();
  46. }
  47. public IEnumerable<DirectoryInfo> GetDirectories(string path)
  48. {
  49. return GetFileSystemEntries(path).OfType<DirectoryInfo>();
  50. }
  51. public FileInfo GetFile(string path)
  52. {
  53. var directory = Path.GetDirectoryName(path);
  54. var filename = Path.GetFileName(path);
  55. return GetFiles(directory).FirstOrDefault(i => string.Equals(i.Name, filename, StringComparison.OrdinalIgnoreCase));
  56. }
  57. public DirectoryInfo GetDirectory(string path)
  58. {
  59. var directory = Path.GetDirectoryName(path);
  60. var name = Path.GetFileName(path);
  61. return GetDirectories(directory).FirstOrDefault(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  62. }
  63. }
  64. }