Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using Microsoft.Extensions.FileProviders;
- using Microsoft.Extensions.Primitives;
- // ReSharper disable once CheckNamespace
- namespace kwd.gist
- {
- /// <summary>
- /// Resolves file system paths using case-aware path.
- /// </summary>
- public class CaseAwareFileProvider : IFileProvider, IDisposable
- {
- private readonly PhysicalFileProvider _provider;
- public CaseAwareFileProvider(string root)
- {
- if (!Path.IsPathRooted(root))
- {
- throw new ArgumentException("The path must be absolute.", nameof(root));
- }
- var pathRoot = Path.GetPathRoot(root);
- var matchCase = ResolvePath(pathRoot, root.Substring(pathRoot.Length));
- _provider = new PhysicalFileProvider(matchCase);
- }
- public string Root => _provider.Root;
- public IFileInfo GetFileInfo(string subpath)
- {
- var matchCase = ResolvePath(_provider.Root, subpath)
- .Substring(_provider.Root.Length);
- return _provider.GetFileInfo(matchCase);
- }
- public IDirectoryContents GetDirectoryContents(string subpath)
- {
- var matchCase = ResolvePath(_provider.Root, subpath)
- .Substring(_provider.Root.Length);
- return _provider.GetDirectoryContents(matchCase);
- }
- public IChangeToken Watch(string filter) =>
- _provider.Watch(filter);
- public void Dispose() => _provider.Dispose();
- private static string ResolvePath(string root, params string[] subPath)
- {
- root = root ?? string.Empty;
- if (root != string.Empty && !Directory.Exists(root))
- {
- return Path.Combine(root, Path.Combine(subPath));
- }
- var pathSegments = subPath
- .SelectMany(x => x.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
- .Where(x => !string.IsNullOrEmpty(x))
- .ToArray();
- var segments = new Queue<string>(pathSegments);
- var cur = root;
- while (segments.Any())
- {
- var next = segments.Dequeue();
- var part = Path.GetFileName(Directory.GetFileSystemEntries(cur, next).FirstOrDefault());
- if (part != null)
- {
- cur = Path.Combine(cur, part);
- }
- else
- {
- cur = Path.Combine(new[]
- {cur, next}.Concat(segments).ToArray());
- break;
- }
- }
- return cur;
- }
- }
- }
Add Comment
Please, Sign In to add comment