Files.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. namespace OpenVIII
  7. {
  8. namespace Movie
  9. {
  10. public struct Files : IEnumerable<string>
  11. {
  12. #region Fields
  13. private static readonly string[] Extensions = new string[] { ".avi", ".mkv", ".mp4", ".bik" };
  14. private static Directories Directories;
  15. private static List<string> s_files;
  16. #endregion Fields
  17. #region Properties
  18. public static int Count => _Files.Count;
  19. private static List<string> _Files { get { Init(); return s_files; } set => s_files = value; }
  20. #endregion Properties
  21. #region Indexers
  22. public string this[int i] => At(i);
  23. #endregion Indexers
  24. #region Methods
  25. public static string At(int i) => _Files[i];
  26. public static bool Exists(int i) => Count > i && i >= 0 && File.Exists(_Files[i]);
  27. public static void Init()
  28. {
  29. if (s_files == null /*|| s_files.Count == 0*/)
  30. {
  31. //Gather all movie files.
  32. s_files = (from directory in Directories
  33. where Directory.Exists(directory)
  34. from file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories)
  35. from extension in Extensions
  36. where file.EndsWith(extension, StringComparison.OrdinalIgnoreCase)
  37. orderby Path.GetFileNameWithoutExtension(file) ascending
  38. select file).ToList();
  39. //Remove duplicate movies ignoring extension that have same name.
  40. (from s1 in _Files.Select((Value, Key) => new { Key, Value })
  41. from s2 in _Files.Select((Value, Key) => new { Key, Value })
  42. where s1.Key < s2.Key
  43. where Path.GetFileNameWithoutExtension(s1.Value).Equals(Path.GetFileNameWithoutExtension(s2.Value), StringComparison.OrdinalIgnoreCase)
  44. orderby s2.Key descending
  45. select s2.Key).ForEach(Key => s_files.RemoveAt(Key));
  46. }
  47. }
  48. public IEnumerator GetEnumerator() => _Files.GetEnumerator();
  49. IEnumerator<string> IEnumerable<string>.GetEnumerator() => _Files.GetEnumerator();
  50. #endregion Methods
  51. }
  52. }
  53. }