Guest User

Untitled

a guest
Jan 2nd, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5.  
  6. using Microsoft.Extensions.FileProviders;
  7. using Microsoft.Extensions.Primitives;
  8.  
  9. // ReSharper disable once CheckNamespace
  10. namespace kwd.gist
  11. {
  12. /// <summary>
  13. /// Resolves file system paths using case-aware path.
  14. /// </summary>
  15. public class CaseAwareFileProvider : IFileProvider, IDisposable
  16. {
  17. private readonly PhysicalFileProvider _provider;
  18.  
  19. public CaseAwareFileProvider(string root)
  20. {
  21. if (!Path.IsPathRooted(root))
  22. {
  23. throw new ArgumentException("The path must be absolute.", nameof(root));
  24. }
  25.  
  26. var pathRoot = Path.GetPathRoot(root);
  27.  
  28. var matchCase = ResolvePath(pathRoot, root.Substring(pathRoot.Length));
  29.  
  30. _provider = new PhysicalFileProvider(matchCase);
  31. }
  32.  
  33. public string Root => _provider.Root;
  34.  
  35. public IFileInfo GetFileInfo(string subpath)
  36. {
  37. var matchCase = ResolvePath(_provider.Root, subpath)
  38. .Substring(_provider.Root.Length);
  39.  
  40. return _provider.GetFileInfo(matchCase);
  41. }
  42.  
  43. public IDirectoryContents GetDirectoryContents(string subpath)
  44. {
  45. var matchCase = ResolvePath(_provider.Root, subpath)
  46. .Substring(_provider.Root.Length);
  47.  
  48. return _provider.GetDirectoryContents(matchCase);
  49. }
  50.  
  51. public IChangeToken Watch(string filter) =>
  52. _provider.Watch(filter);
  53.  
  54. public void Dispose() => _provider.Dispose();
  55.  
  56. private static string ResolvePath(string root, params string[] subPath)
  57. {
  58. root = root ?? string.Empty;
  59.  
  60. if (root != string.Empty && !Directory.Exists(root))
  61. {
  62. return Path.Combine(root, Path.Combine(subPath));
  63. }
  64.  
  65. var pathSegments = subPath
  66. .SelectMany(x => x.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
  67. .Where(x => !string.IsNullOrEmpty(x))
  68. .ToArray();
  69.  
  70. var segments = new Queue<string>(pathSegments);
  71. var cur = root;
  72.  
  73. while (segments.Any())
  74. {
  75. var next = segments.Dequeue();
  76. var part = Path.GetFileName(Directory.GetFileSystemEntries(cur, next).FirstOrDefault());
  77. if (part != null)
  78. {
  79. cur = Path.Combine(cur, part);
  80. }
  81. else
  82. {
  83. cur = Path.Combine(new[]
  84. {cur, next}.Concat(segments).ToArray());
  85. break;
  86. }
  87. }
  88.  
  89. return cur;
  90. }
  91. }
  92. }
Add Comment
Please, Sign In to add comment