ManagedFileSystem.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using Jellyfin.Extensions;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.IO;
  9. using Microsoft.Extensions.Logging;
  10. namespace Emby.Server.Implementations.IO
  11. {
  12. /// <summary>
  13. /// Class ManagedFileSystem.
  14. /// </summary>
  15. public class ManagedFileSystem : IFileSystem
  16. {
  17. private readonly ILogger<ManagedFileSystem> _logger;
  18. private readonly List<IShortcutHandler> _shortcutHandlers = new List<IShortcutHandler>();
  19. private readonly string _tempPath;
  20. private static readonly bool _isEnvironmentCaseInsensitive = OperatingSystem.IsWindows();
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="ManagedFileSystem"/> class.
  23. /// </summary>
  24. /// <param name="logger">The <see cref="ILogger"/> instance to use.</param>
  25. /// <param name="applicationPaths">The <see cref="IApplicationPaths"/> instance to use.</param>
  26. public ManagedFileSystem(
  27. ILogger<ManagedFileSystem> logger,
  28. IApplicationPaths applicationPaths)
  29. {
  30. _logger = logger;
  31. _tempPath = applicationPaths.TempDirectory;
  32. }
  33. /// <inheritdoc />
  34. public virtual void AddShortcutHandler(IShortcutHandler handler)
  35. {
  36. _shortcutHandlers.Add(handler);
  37. }
  38. /// <summary>
  39. /// Determines whether the specified filename is shortcut.
  40. /// </summary>
  41. /// <param name="filename">The filename.</param>
  42. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  43. /// <exception cref="ArgumentNullException"><paramref name="filename"/> is <c>null</c>.</exception>
  44. public virtual bool IsShortcut(string filename)
  45. {
  46. ArgumentException.ThrowIfNullOrEmpty(filename);
  47. var extension = Path.GetExtension(filename);
  48. return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  49. }
  50. /// <summary>
  51. /// Resolves the shortcut.
  52. /// </summary>
  53. /// <param name="filename">The filename.</param>
  54. /// <returns>System.String.</returns>
  55. /// <exception cref="ArgumentNullException"><paramref name="filename"/> is <c>null</c>.</exception>
  56. public virtual string? ResolveShortcut(string filename)
  57. {
  58. ArgumentException.ThrowIfNullOrEmpty(filename);
  59. var extension = Path.GetExtension(filename);
  60. var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  61. return handler?.Resolve(filename);
  62. }
  63. /// <inheritdoc />
  64. public virtual string MakeAbsolutePath(string folderPath, string filePath)
  65. {
  66. // path is actually a stream
  67. if (string.IsNullOrWhiteSpace(filePath) || filePath.Contains("://", StringComparison.Ordinal))
  68. {
  69. return filePath;
  70. }
  71. if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/')
  72. {
  73. // absolute local path
  74. return filePath;
  75. }
  76. // unc path
  77. if (filePath.StartsWith("\\\\", StringComparison.Ordinal))
  78. {
  79. return filePath;
  80. }
  81. var firstChar = filePath[0];
  82. if (firstChar == '/')
  83. {
  84. // for this we don't really know
  85. return filePath;
  86. }
  87. // relative path
  88. if (firstChar == '\\')
  89. {
  90. filePath = filePath.Substring(1);
  91. }
  92. try
  93. {
  94. return Path.GetFullPath(Path.Combine(folderPath, filePath));
  95. }
  96. catch (ArgumentException)
  97. {
  98. return filePath;
  99. }
  100. catch (PathTooLongException)
  101. {
  102. return filePath;
  103. }
  104. catch (NotSupportedException)
  105. {
  106. return filePath;
  107. }
  108. }
  109. /// <summary>
  110. /// Creates the shortcut.
  111. /// </summary>
  112. /// <param name="shortcutPath">The shortcut path.</param>
  113. /// <param name="target">The target.</param>
  114. /// <exception cref="ArgumentNullException">The shortcutPath or target is null.</exception>
  115. public virtual void CreateShortcut(string shortcutPath, string target)
  116. {
  117. ArgumentException.ThrowIfNullOrEmpty(shortcutPath);
  118. ArgumentException.ThrowIfNullOrEmpty(target);
  119. var extension = Path.GetExtension(shortcutPath);
  120. var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  121. if (handler is not null)
  122. {
  123. handler.Create(shortcutPath, target);
  124. }
  125. else
  126. {
  127. throw new NotImplementedException();
  128. }
  129. }
  130. /// <summary>
  131. /// Returns a <see cref="FileSystemMetadata"/> object for the specified file or directory path.
  132. /// </summary>
  133. /// <param name="path">A path to a file or directory.</param>
  134. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  135. /// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
  136. /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
  137. public virtual FileSystemMetadata GetFileSystemInfo(string path)
  138. {
  139. // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
  140. if (Path.HasExtension(path))
  141. {
  142. var fileInfo = new FileInfo(path);
  143. if (fileInfo.Exists)
  144. {
  145. return GetFileSystemMetadata(fileInfo);
  146. }
  147. return GetFileSystemMetadata(new DirectoryInfo(path));
  148. }
  149. else
  150. {
  151. var fileInfo = new DirectoryInfo(path);
  152. if (fileInfo.Exists)
  153. {
  154. return GetFileSystemMetadata(fileInfo);
  155. }
  156. return GetFileSystemMetadata(new FileInfo(path));
  157. }
  158. }
  159. /// <summary>
  160. /// Returns a <see cref="FileSystemMetadata"/> object for the specified file path.
  161. /// </summary>
  162. /// <param name="path">A path to a file.</param>
  163. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  164. /// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
  165. /// <see cref="FileSystemMetadata.IsDirectory"/> property and the <see cref="FileSystemMetadata.Exists"/> property will both be set to false.</para>
  166. /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
  167. public virtual FileSystemMetadata GetFileInfo(string path)
  168. {
  169. var fileInfo = new FileInfo(path);
  170. return GetFileSystemMetadata(fileInfo);
  171. }
  172. /// <summary>
  173. /// Returns a <see cref="FileSystemMetadata"/> object for the specified directory path.
  174. /// </summary>
  175. /// <param name="path">A path to a directory.</param>
  176. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  177. /// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata"/> object's
  178. /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and the <see cref="FileSystemMetadata.Exists"/> property will be set to false.</para>
  179. /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
  180. public virtual FileSystemMetadata GetDirectoryInfo(string path)
  181. {
  182. var fileInfo = new DirectoryInfo(path);
  183. return GetFileSystemMetadata(fileInfo);
  184. }
  185. private FileSystemMetadata GetFileSystemMetadata(FileSystemInfo info)
  186. {
  187. var result = new FileSystemMetadata
  188. {
  189. Exists = info.Exists,
  190. FullName = info.FullName,
  191. Extension = info.Extension,
  192. Name = info.Name
  193. };
  194. if (result.Exists)
  195. {
  196. result.IsDirectory = info is DirectoryInfo || (info.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
  197. // if (!result.IsDirectory)
  198. // {
  199. // result.IsHidden = (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
  200. // }
  201. if (info is FileInfo fileInfo)
  202. {
  203. result.Length = fileInfo.Length;
  204. // Issue #2354 get the size of files behind symbolic links. Also Enum.HasFlag is bad as it boxes!
  205. if ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
  206. {
  207. try
  208. {
  209. using (var fileHandle = File.OpenHandle(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  210. {
  211. result.Length = RandomAccess.GetLength(fileHandle);
  212. }
  213. }
  214. catch (FileNotFoundException ex)
  215. {
  216. // Dangling symlinks cannot be detected before opening the file unfortunately...
  217. _logger.LogError(ex, "Reading the file size of the symlink at {Path} failed. Marking the file as not existing.", fileInfo.FullName);
  218. result.Exists = false;
  219. }
  220. catch (UnauthorizedAccessException ex)
  221. {
  222. _logger.LogError(ex, "Reading the file at {Path} failed due to a permissions exception.", fileInfo.FullName);
  223. }
  224. }
  225. }
  226. result.CreationTimeUtc = GetCreationTimeUtc(info);
  227. result.LastWriteTimeUtc = GetLastWriteTimeUtc(info);
  228. }
  229. else
  230. {
  231. result.IsDirectory = info is DirectoryInfo;
  232. }
  233. return result;
  234. }
  235. private static ExtendedFileSystemInfo GetExtendedFileSystemInfo(string path)
  236. {
  237. var result = new ExtendedFileSystemInfo();
  238. var info = new FileInfo(path);
  239. if (info.Exists)
  240. {
  241. result.Exists = true;
  242. var attributes = info.Attributes;
  243. result.IsHidden = (attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
  244. result.IsReadOnly = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
  245. }
  246. return result;
  247. }
  248. /// <summary>
  249. /// Takes a filename and removes invalid characters.
  250. /// </summary>
  251. /// <param name="filename">The filename.</param>
  252. /// <returns>System.String.</returns>
  253. /// <exception cref="ArgumentNullException">The filename is null.</exception>
  254. public string GetValidFilename(string filename)
  255. {
  256. var invalid = Path.GetInvalidFileNameChars();
  257. var first = filename.IndexOfAny(invalid);
  258. if (first == -1)
  259. {
  260. // Fast path for clean strings
  261. return filename;
  262. }
  263. return string.Create(
  264. filename.Length,
  265. (filename, invalid, first),
  266. (chars, state) =>
  267. {
  268. state.filename.AsSpan().CopyTo(chars);
  269. chars[state.first++] = ' ';
  270. var len = chars.Length;
  271. foreach (var c in state.invalid)
  272. {
  273. for (int i = state.first; i < len; i++)
  274. {
  275. if (chars[i] == c)
  276. {
  277. chars[i] = ' ';
  278. }
  279. }
  280. }
  281. });
  282. }
  283. /// <summary>
  284. /// Gets the creation time UTC.
  285. /// </summary>
  286. /// <param name="info">The info.</param>
  287. /// <returns>DateTime.</returns>
  288. public DateTime GetCreationTimeUtc(FileSystemInfo info)
  289. {
  290. // This could throw an error on some file systems that have dates out of range
  291. try
  292. {
  293. return info.CreationTimeUtc;
  294. }
  295. catch (Exception ex)
  296. {
  297. _logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
  298. return DateTime.MinValue;
  299. }
  300. }
  301. /// <summary>
  302. /// Gets the creation time UTC.
  303. /// </summary>
  304. /// <param name="path">The path.</param>
  305. /// <returns>DateTime.</returns>
  306. public virtual DateTime GetCreationTimeUtc(string path)
  307. {
  308. return GetCreationTimeUtc(GetFileSystemInfo(path));
  309. }
  310. /// <inheritdoc />
  311. public virtual DateTime GetCreationTimeUtc(FileSystemMetadata info)
  312. {
  313. return info.CreationTimeUtc;
  314. }
  315. /// <inheritdoc />
  316. public virtual DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
  317. {
  318. return info.LastWriteTimeUtc;
  319. }
  320. /// <summary>
  321. /// Gets the creation time UTC.
  322. /// </summary>
  323. /// <param name="info">The info.</param>
  324. /// <returns>DateTime.</returns>
  325. public DateTime GetLastWriteTimeUtc(FileSystemInfo info)
  326. {
  327. // This could throw an error on some file systems that have dates out of range
  328. try
  329. {
  330. return info.LastWriteTimeUtc;
  331. }
  332. catch (Exception ex)
  333. {
  334. _logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
  335. return DateTime.MinValue;
  336. }
  337. }
  338. /// <summary>
  339. /// Gets the last write time UTC.
  340. /// </summary>
  341. /// <param name="path">The path.</param>
  342. /// <returns>DateTime.</returns>
  343. public virtual DateTime GetLastWriteTimeUtc(string path)
  344. {
  345. return GetLastWriteTimeUtc(GetFileSystemInfo(path));
  346. }
  347. /// <inheritdoc />
  348. public virtual void SetHidden(string path, bool isHidden)
  349. {
  350. if (!OperatingSystem.IsWindows())
  351. {
  352. return;
  353. }
  354. var info = GetExtendedFileSystemInfo(path);
  355. if (info.Exists && info.IsHidden != isHidden)
  356. {
  357. if (isHidden)
  358. {
  359. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
  360. }
  361. else
  362. {
  363. var attributes = File.GetAttributes(path);
  364. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  365. File.SetAttributes(path, attributes);
  366. }
  367. }
  368. }
  369. /// <inheritdoc />
  370. public virtual void SetAttributes(string path, bool isHidden, bool readOnly)
  371. {
  372. if (!OperatingSystem.IsWindows())
  373. {
  374. return;
  375. }
  376. var info = GetExtendedFileSystemInfo(path);
  377. if (!info.Exists)
  378. {
  379. return;
  380. }
  381. if (info.IsReadOnly == readOnly && info.IsHidden == isHidden)
  382. {
  383. return;
  384. }
  385. var attributes = File.GetAttributes(path);
  386. if (readOnly)
  387. {
  388. attributes |= FileAttributes.ReadOnly;
  389. }
  390. else
  391. {
  392. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  393. }
  394. if (isHidden)
  395. {
  396. attributes |= FileAttributes.Hidden;
  397. }
  398. else
  399. {
  400. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  401. }
  402. File.SetAttributes(path, attributes);
  403. }
  404. private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
  405. {
  406. return attributes & ~attributesToRemove;
  407. }
  408. /// <summary>
  409. /// Swaps the files.
  410. /// </summary>
  411. /// <param name="file1">The file1.</param>
  412. /// <param name="file2">The file2.</param>
  413. public virtual void SwapFiles(string file1, string file2)
  414. {
  415. ArgumentException.ThrowIfNullOrEmpty(file1);
  416. ArgumentException.ThrowIfNullOrEmpty(file2);
  417. var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));
  418. // Copying over will fail against hidden files
  419. SetHidden(file1, false);
  420. SetHidden(file2, false);
  421. Directory.CreateDirectory(_tempPath);
  422. File.Copy(file1, temp1, true);
  423. File.Copy(file2, file1, true);
  424. File.Copy(temp1, file2, true);
  425. }
  426. /// <inheritdoc />
  427. public virtual bool ContainsSubPath(string parentPath, string path)
  428. {
  429. ArgumentException.ThrowIfNullOrEmpty(parentPath);
  430. ArgumentException.ThrowIfNullOrEmpty(path);
  431. return path.Contains(
  432. Path.TrimEndingDirectorySeparator(parentPath) + Path.DirectorySeparatorChar,
  433. _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
  434. }
  435. /// <inheritdoc />
  436. public virtual string NormalizePath(string path)
  437. {
  438. ArgumentException.ThrowIfNullOrEmpty(path);
  439. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  440. {
  441. return path;
  442. }
  443. return Path.TrimEndingDirectorySeparator(path);
  444. }
  445. /// <inheritdoc />
  446. public virtual bool AreEqual(string path1, string path2)
  447. {
  448. return string.Equals(
  449. NormalizePath(path1),
  450. NormalizePath(path2),
  451. _isEnvironmentCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
  452. }
  453. /// <inheritdoc />
  454. public virtual string GetFileNameWithoutExtension(FileSystemMetadata info)
  455. {
  456. if (info.IsDirectory)
  457. {
  458. return info.Name;
  459. }
  460. return Path.GetFileNameWithoutExtension(info.FullName);
  461. }
  462. /// <inheritdoc />
  463. public virtual bool IsPathFile(string path)
  464. {
  465. if (path.Contains("://", StringComparison.OrdinalIgnoreCase)
  466. && !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  467. {
  468. return false;
  469. }
  470. return true;
  471. }
  472. /// <inheritdoc />
  473. public virtual void DeleteFile(string path)
  474. {
  475. SetAttributes(path, false, false);
  476. File.Delete(path);
  477. }
  478. /// <inheritdoc />
  479. public virtual IEnumerable<FileSystemMetadata> GetDrives()
  480. {
  481. // check for ready state to avoid waiting for drives to timeout
  482. // some drives on linux have no actual size or are used for other purposes
  483. return DriveInfo.GetDrives()
  484. .Where(
  485. d => (d.DriveType == DriveType.Fixed || d.DriveType == DriveType.Network || d.DriveType == DriveType.Removable)
  486. && d.IsReady
  487. && d.TotalSize != 0)
  488. .Select(d => new FileSystemMetadata
  489. {
  490. Name = d.Name,
  491. FullName = d.RootDirectory.FullName,
  492. IsDirectory = true
  493. });
  494. }
  495. /// <inheritdoc />
  496. public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  497. {
  498. return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", GetEnumerationOptions(recursive)));
  499. }
  500. /// <inheritdoc />
  501. public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
  502. {
  503. return GetFiles(path, null, false, recursive);
  504. }
  505. /// <inheritdoc />
  506. public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string>? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  507. {
  508. var enumerationOptions = GetEnumerationOptions(recursive);
  509. // On linux and osx the search pattern is case sensitive
  510. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  511. if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions is not null && extensions.Count == 1)
  512. {
  513. return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], enumerationOptions));
  514. }
  515. var files = new DirectoryInfo(path).EnumerateFiles("*", enumerationOptions);
  516. if (extensions is not null && extensions.Count > 0)
  517. {
  518. files = files.Where(i =>
  519. {
  520. var ext = i.Extension.AsSpan();
  521. if (ext.IsEmpty)
  522. {
  523. return false;
  524. }
  525. return extensions.Contains(ext, StringComparison.OrdinalIgnoreCase);
  526. });
  527. }
  528. return ToMetadata(files);
  529. }
  530. /// <inheritdoc />
  531. public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  532. {
  533. var directoryInfo = new DirectoryInfo(path);
  534. var enumerationOptions = GetEnumerationOptions(recursive);
  535. return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", enumerationOptions));
  536. }
  537. private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
  538. {
  539. return infos.Select(GetFileSystemMetadata);
  540. }
  541. /// <inheritdoc />
  542. public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  543. {
  544. return Directory.EnumerateDirectories(path, "*", GetEnumerationOptions(recursive));
  545. }
  546. /// <inheritdoc />
  547. public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false)
  548. {
  549. return GetFilePaths(path, null, false, recursive);
  550. }
  551. /// <inheritdoc />
  552. public virtual IEnumerable<string> GetFilePaths(string path, string[]? extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  553. {
  554. var enumerationOptions = GetEnumerationOptions(recursive);
  555. // On linux and osx the search pattern is case sensitive
  556. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  557. if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions is not null && extensions.Length == 1)
  558. {
  559. return Directory.EnumerateFiles(path, "*" + extensions[0], enumerationOptions);
  560. }
  561. var files = Directory.EnumerateFiles(path, "*", enumerationOptions);
  562. if (extensions is not null && extensions.Length > 0)
  563. {
  564. files = files.Where(i =>
  565. {
  566. var ext = Path.GetExtension(i.AsSpan());
  567. if (ext.IsEmpty)
  568. {
  569. return false;
  570. }
  571. return extensions.Contains(ext, StringComparison.OrdinalIgnoreCase);
  572. });
  573. }
  574. return files;
  575. }
  576. /// <inheritdoc />
  577. public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  578. {
  579. return Directory.EnumerateFileSystemEntries(path, "*", GetEnumerationOptions(recursive));
  580. }
  581. /// <inheritdoc />
  582. public virtual bool DirectoryExists(string path)
  583. {
  584. return Directory.Exists(path);
  585. }
  586. /// <inheritdoc />
  587. public virtual bool FileExists(string path)
  588. {
  589. return File.Exists(path);
  590. }
  591. private EnumerationOptions GetEnumerationOptions(bool recursive)
  592. {
  593. return new EnumerationOptions
  594. {
  595. RecurseSubdirectories = recursive,
  596. IgnoreInaccessible = true,
  597. // Don't skip any files.
  598. AttributesToSkip = 0
  599. };
  600. }
  601. }
  602. }