2
0

ManagedFileSystem.cs 26 KB

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