ManagedFileSystem.cs 26 KB

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