ManagedFileSystem.cs 25 KB

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