ManagedFileSystem.cs 27 KB

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