ManagedFileSystem.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using MediaBrowser.Model.IO;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.System;
  9. namespace Emby.Common.Implementations.IO
  10. {
  11. /// <summary>
  12. /// Class ManagedFileSystem
  13. /// </summary>
  14. public class ManagedFileSystem : IFileSystem
  15. {
  16. protected ILogger Logger;
  17. private readonly bool _supportsAsyncFileStreams;
  18. private char[] _invalidFileNameChars;
  19. private readonly List<IShortcutHandler> _shortcutHandlers = new List<IShortcutHandler>();
  20. private bool EnableFileSystemRequestConcat;
  21. private string _tempPath;
  22. private SharpCifsFileSystem _sharpCifsFileSystem;
  23. public ManagedFileSystem(ILogger logger, IEnvironmentInfo environmentInfo, string tempPath)
  24. {
  25. Logger = logger;
  26. _supportsAsyncFileStreams = true;
  27. _tempPath = tempPath;
  28. // On Linux, this needs to be true or symbolic links are ignored
  29. EnableFileSystemRequestConcat = environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows &&
  30. environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.OSX;
  31. SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
  32. _sharpCifsFileSystem = new SharpCifsFileSystem(environmentInfo.OperatingSystem);
  33. }
  34. public void AddShortcutHandler(IShortcutHandler handler)
  35. {
  36. _shortcutHandlers.Add(handler);
  37. }
  38. protected void SetInvalidFileNameChars(bool enableManagedInvalidFileNameChars)
  39. {
  40. if (enableManagedInvalidFileNameChars)
  41. {
  42. _invalidFileNameChars = Path.GetInvalidFileNameChars();
  43. }
  44. else
  45. {
  46. // GetInvalidFileNameChars is less restrictive in Linux/Mac than Windows, this mimic Windows behavior for mono under Linux/Mac.
  47. _invalidFileNameChars = new char[41] { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  48. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  49. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  50. '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' };
  51. }
  52. }
  53. public char DirectorySeparatorChar
  54. {
  55. get
  56. {
  57. return Path.DirectorySeparatorChar;
  58. }
  59. }
  60. public string GetFullPath(string path)
  61. {
  62. return Path.GetFullPath(path);
  63. }
  64. /// <summary>
  65. /// Determines whether the specified filename is shortcut.
  66. /// </summary>
  67. /// <param name="filename">The filename.</param>
  68. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  69. /// <exception cref="System.ArgumentNullException">filename</exception>
  70. public virtual bool IsShortcut(string filename)
  71. {
  72. if (string.IsNullOrEmpty(filename))
  73. {
  74. throw new ArgumentNullException("filename");
  75. }
  76. var extension = Path.GetExtension(filename);
  77. return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  78. }
  79. /// <summary>
  80. /// Resolves the shortcut.
  81. /// </summary>
  82. /// <param name="filename">The filename.</param>
  83. /// <returns>System.String.</returns>
  84. /// <exception cref="System.ArgumentNullException">filename</exception>
  85. public virtual string ResolveShortcut(string filename)
  86. {
  87. if (string.IsNullOrEmpty(filename))
  88. {
  89. throw new ArgumentNullException("filename");
  90. }
  91. var extension = Path.GetExtension(filename);
  92. var handler = _shortcutHandlers.FirstOrDefault(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  93. if (handler != null)
  94. {
  95. return handler.Resolve(filename);
  96. }
  97. return null;
  98. }
  99. /// <summary>
  100. /// Creates the shortcut.
  101. /// </summary>
  102. /// <param name="shortcutPath">The shortcut path.</param>
  103. /// <param name="target">The target.</param>
  104. /// <exception cref="System.ArgumentNullException">
  105. /// shortcutPath
  106. /// or
  107. /// target
  108. /// </exception>
  109. public void CreateShortcut(string shortcutPath, string target)
  110. {
  111. if (string.IsNullOrEmpty(shortcutPath))
  112. {
  113. throw new ArgumentNullException("shortcutPath");
  114. }
  115. if (string.IsNullOrEmpty(target))
  116. {
  117. throw new ArgumentNullException("target");
  118. }
  119. var extension = Path.GetExtension(shortcutPath);
  120. var handler = _shortcutHandlers.FirstOrDefault(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  121. if (handler != null)
  122. {
  123. handler.Create(shortcutPath, target);
  124. }
  125. else
  126. {
  127. throw new NotImplementedException();
  128. }
  129. }
  130. /// <summary>
  131. /// Returns a <see cref="FileSystemMetadata"/> object for the specified file or directory path.
  132. /// </summary>
  133. /// <param name="path">A path to a file or directory.</param>
  134. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  135. /// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
  136. /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
  137. public FileSystemMetadata GetFileSystemInfo(string path)
  138. {
  139. if (string.IsNullOrEmpty(path))
  140. {
  141. throw new ArgumentNullException("path");
  142. }
  143. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  144. {
  145. return _sharpCifsFileSystem.GetFileSystemInfo(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 FileSystemMetadata GetFileInfo(string path)
  176. {
  177. if (string.IsNullOrEmpty(path))
  178. {
  179. throw new ArgumentNullException("path");
  180. }
  181. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  182. {
  183. return _sharpCifsFileSystem.GetFileInfo(path);
  184. }
  185. var fileInfo = new FileInfo(path);
  186. return GetFileSystemMetadata(fileInfo);
  187. }
  188. /// <summary>
  189. /// Returns a <see cref="FileSystemMetadata"/> object for the specified directory path.
  190. /// </summary>
  191. /// <param name="path">A path to a directory.</param>
  192. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  193. /// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata"/> object's
  194. /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and the <see cref="FileSystemMetadata.Exists"/> property will be set to false.</para>
  195. /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
  196. public FileSystemMetadata GetDirectoryInfo(string path)
  197. {
  198. if (string.IsNullOrEmpty(path))
  199. {
  200. throw new ArgumentNullException("path");
  201. }
  202. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  203. {
  204. return _sharpCifsFileSystem.GetDirectoryInfo(path);
  205. }
  206. var fileInfo = new DirectoryInfo(path);
  207. return GetFileSystemMetadata(fileInfo);
  208. }
  209. private FileSystemMetadata GetFileSystemMetadata(FileSystemInfo info)
  210. {
  211. var result = new FileSystemMetadata();
  212. result.Exists = info.Exists;
  213. result.FullName = info.FullName;
  214. result.Extension = info.Extension;
  215. result.Name = info.Name;
  216. if (result.Exists)
  217. {
  218. var attributes = info.Attributes;
  219. result.IsDirectory = info is DirectoryInfo || (attributes & FileAttributes.Directory) == FileAttributes.Directory;
  220. result.IsHidden = (attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
  221. result.IsReadOnly = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
  222. var fileInfo = info as FileInfo;
  223. if (fileInfo != null)
  224. {
  225. result.Length = fileInfo.Length;
  226. result.DirectoryName = fileInfo.DirectoryName;
  227. }
  228. result.CreationTimeUtc = GetCreationTimeUtc(info);
  229. result.LastWriteTimeUtc = GetLastWriteTimeUtc(info);
  230. }
  231. else
  232. {
  233. result.IsDirectory = info is DirectoryInfo;
  234. }
  235. return result;
  236. }
  237. /// <summary>
  238. /// The space char
  239. /// </summary>
  240. private const char SpaceChar = ' ';
  241. /// <summary>
  242. /// Takes a filename and removes invalid characters
  243. /// </summary>
  244. /// <param name="filename">The filename.</param>
  245. /// <returns>System.String.</returns>
  246. /// <exception cref="System.ArgumentNullException">filename</exception>
  247. public string GetValidFilename(string filename)
  248. {
  249. if (string.IsNullOrEmpty(filename))
  250. {
  251. throw new ArgumentNullException("filename");
  252. }
  253. var builder = new StringBuilder(filename);
  254. foreach (var c in _invalidFileNameChars)
  255. {
  256. builder = builder.Replace(c, SpaceChar);
  257. }
  258. return builder.ToString();
  259. }
  260. /// <summary>
  261. /// Gets the creation time UTC.
  262. /// </summary>
  263. /// <param name="info">The info.</param>
  264. /// <returns>DateTime.</returns>
  265. public DateTime GetCreationTimeUtc(FileSystemInfo info)
  266. {
  267. // This could throw an error on some file systems that have dates out of range
  268. try
  269. {
  270. return info.CreationTimeUtc;
  271. }
  272. catch (Exception ex)
  273. {
  274. Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName);
  275. return DateTime.MinValue;
  276. }
  277. }
  278. /// <summary>
  279. /// Gets the creation time UTC.
  280. /// </summary>
  281. /// <param name="path">The path.</param>
  282. /// <returns>DateTime.</returns>
  283. public DateTime GetCreationTimeUtc(string path)
  284. {
  285. return GetCreationTimeUtc(GetFileSystemInfo(path));
  286. }
  287. public DateTime GetCreationTimeUtc(FileSystemMetadata info)
  288. {
  289. return info.CreationTimeUtc;
  290. }
  291. public DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
  292. {
  293. return info.LastWriteTimeUtc;
  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 GetLastWriteTimeUtc(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.LastWriteTimeUtc;
  306. }
  307. catch (Exception ex)
  308. {
  309. Logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName);
  310. return DateTime.MinValue;
  311. }
  312. }
  313. /// <summary>
  314. /// Gets the last write time UTC.
  315. /// </summary>
  316. /// <param name="path">The path.</param>
  317. /// <returns>DateTime.</returns>
  318. public DateTime GetLastWriteTimeUtc(string path)
  319. {
  320. return GetLastWriteTimeUtc(GetFileSystemInfo(path));
  321. }
  322. /// <summary>
  323. /// Gets the file stream.
  324. /// </summary>
  325. /// <param name="path">The path.</param>
  326. /// <param name="mode">The mode.</param>
  327. /// <param name="access">The access.</param>
  328. /// <param name="share">The share.</param>
  329. /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
  330. /// <returns>FileStream.</returns>
  331. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
  332. {
  333. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  334. {
  335. return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
  336. }
  337. if (_supportsAsyncFileStreams && isAsync)
  338. {
  339. return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 262144, true);
  340. }
  341. return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 262144);
  342. }
  343. private FileMode GetFileMode(FileOpenMode mode)
  344. {
  345. switch (mode)
  346. {
  347. //case FileOpenMode.Append:
  348. // return FileMode.Append;
  349. case FileOpenMode.Create:
  350. return FileMode.Create;
  351. case FileOpenMode.CreateNew:
  352. return FileMode.CreateNew;
  353. case FileOpenMode.Open:
  354. return FileMode.Open;
  355. case FileOpenMode.OpenOrCreate:
  356. return FileMode.OpenOrCreate;
  357. //case FileOpenMode.Truncate:
  358. // return FileMode.Truncate;
  359. default:
  360. throw new Exception("Unrecognized FileOpenMode");
  361. }
  362. }
  363. private FileAccess GetFileAccess(FileAccessMode mode)
  364. {
  365. switch (mode)
  366. {
  367. //case FileAccessMode.ReadWrite:
  368. // return FileAccess.ReadWrite;
  369. case FileAccessMode.Write:
  370. return FileAccess.Write;
  371. case FileAccessMode.Read:
  372. return FileAccess.Read;
  373. default:
  374. throw new Exception("Unrecognized FileAccessMode");
  375. }
  376. }
  377. private FileShare GetFileShare(FileShareMode mode)
  378. {
  379. switch (mode)
  380. {
  381. case FileShareMode.ReadWrite:
  382. return FileShare.ReadWrite;
  383. case FileShareMode.Write:
  384. return FileShare.Write;
  385. case FileShareMode.Read:
  386. return FileShare.Read;
  387. case FileShareMode.None:
  388. return FileShare.None;
  389. default:
  390. throw new Exception("Unrecognized FileShareMode");
  391. }
  392. }
  393. public void SetHidden(string path, bool isHidden)
  394. {
  395. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  396. {
  397. _sharpCifsFileSystem.SetHidden(path, isHidden);
  398. return;
  399. }
  400. var info = GetFileInfo(path);
  401. if (info.Exists && info.IsHidden != isHidden)
  402. {
  403. if (isHidden)
  404. {
  405. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
  406. }
  407. else
  408. {
  409. FileAttributes attributes = File.GetAttributes(path);
  410. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  411. File.SetAttributes(path, attributes);
  412. }
  413. }
  414. }
  415. public void SetReadOnly(string path, bool isReadOnly)
  416. {
  417. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  418. {
  419. _sharpCifsFileSystem.SetReadOnly(path, isReadOnly);
  420. return;
  421. }
  422. var info = GetFileInfo(path);
  423. if (info.Exists && info.IsReadOnly != isReadOnly)
  424. {
  425. if (isReadOnly)
  426. {
  427. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
  428. }
  429. else
  430. {
  431. FileAttributes attributes = File.GetAttributes(path);
  432. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  433. File.SetAttributes(path, attributes);
  434. }
  435. }
  436. }
  437. private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
  438. {
  439. return attributes & ~attributesToRemove;
  440. }
  441. /// <summary>
  442. /// Swaps the files.
  443. /// </summary>
  444. /// <param name="file1">The file1.</param>
  445. /// <param name="file2">The file2.</param>
  446. public void SwapFiles(string file1, string file2)
  447. {
  448. if (string.IsNullOrEmpty(file1))
  449. {
  450. throw new ArgumentNullException("file1");
  451. }
  452. if (string.IsNullOrEmpty(file2))
  453. {
  454. throw new ArgumentNullException("file2");
  455. }
  456. var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
  457. // Copying over will fail against hidden files
  458. SetHidden(file1, false);
  459. SetHidden(file2, false);
  460. Directory.CreateDirectory(_tempPath);
  461. CopyFile(file1, temp1, true);
  462. CopyFile(file2, file1, true);
  463. CopyFile(temp1, file2, true);
  464. }
  465. private char GetDirectorySeparatorChar(string path)
  466. {
  467. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  468. {
  469. return _sharpCifsFileSystem.GetDirectorySeparatorChar(path);
  470. }
  471. return Path.DirectorySeparatorChar;
  472. }
  473. public bool AreEqual(string path1, string path2)
  474. {
  475. if (path1 == null && path2 == null)
  476. {
  477. return true;
  478. }
  479. if (path1 == null || path2 == null)
  480. {
  481. return false;
  482. }
  483. path1 = path1.TrimEnd(GetDirectorySeparatorChar(path1));
  484. path2 = path2.TrimEnd(GetDirectorySeparatorChar(path2));
  485. return string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase);
  486. }
  487. public bool ContainsSubPath(string parentPath, string path)
  488. {
  489. if (string.IsNullOrEmpty(parentPath))
  490. {
  491. throw new ArgumentNullException("parentPath");
  492. }
  493. if (string.IsNullOrEmpty(path))
  494. {
  495. throw new ArgumentNullException("path");
  496. }
  497. var separatorChar = GetDirectorySeparatorChar(parentPath);
  498. return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  499. }
  500. public bool IsRootPath(string path)
  501. {
  502. if (string.IsNullOrEmpty(path))
  503. {
  504. throw new ArgumentNullException("path");
  505. }
  506. var parent = Path.GetDirectoryName(path);
  507. if (!string.IsNullOrEmpty(parent))
  508. {
  509. return false;
  510. }
  511. return true;
  512. }
  513. public string NormalizePath(string path)
  514. {
  515. if (string.IsNullOrEmpty(path))
  516. {
  517. throw new ArgumentNullException("path");
  518. }
  519. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  520. {
  521. return path;
  522. }
  523. return path.TrimEnd(GetDirectorySeparatorChar(path));
  524. }
  525. public string GetFileNameWithoutExtension(FileSystemMetadata info)
  526. {
  527. if (info.IsDirectory)
  528. {
  529. return info.Name;
  530. }
  531. return Path.GetFileNameWithoutExtension(info.FullName);
  532. }
  533. public string GetFileNameWithoutExtension(string path)
  534. {
  535. return Path.GetFileNameWithoutExtension(path);
  536. }
  537. public bool IsPathFile(string path)
  538. {
  539. if (string.IsNullOrWhiteSpace(path))
  540. {
  541. throw new ArgumentNullException("path");
  542. }
  543. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  544. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  545. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  546. {
  547. return false;
  548. }
  549. return true;
  550. //return Path.IsPathRooted(path);
  551. }
  552. public void DeleteFile(string path)
  553. {
  554. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  555. {
  556. _sharpCifsFileSystem.DeleteFile(path);
  557. return;
  558. }
  559. var fileInfo = GetFileInfo(path);
  560. if (fileInfo.Exists)
  561. {
  562. if (fileInfo.IsHidden)
  563. {
  564. SetHidden(path, false);
  565. }
  566. if (fileInfo.IsReadOnly)
  567. {
  568. SetReadOnly(path, false);
  569. }
  570. }
  571. File.Delete(path);
  572. }
  573. public void DeleteDirectory(string path, bool recursive)
  574. {
  575. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  576. {
  577. _sharpCifsFileSystem.DeleteDirectory(path, recursive);
  578. return;
  579. }
  580. Directory.Delete(path, recursive);
  581. }
  582. public void CreateDirectory(string path)
  583. {
  584. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  585. {
  586. _sharpCifsFileSystem.CreateDirectory(path);
  587. return;
  588. }
  589. Directory.CreateDirectory(path);
  590. }
  591. public List<FileSystemMetadata> GetDrives()
  592. {
  593. // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
  594. return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata
  595. {
  596. Name = GetName(d),
  597. FullName = d.RootDirectory.FullName,
  598. IsDirectory = true
  599. }).ToList();
  600. }
  601. private string GetName(DriveInfo drive)
  602. {
  603. return drive.Name;
  604. }
  605. public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  606. {
  607. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  608. {
  609. return _sharpCifsFileSystem.GetDirectories(path, recursive);
  610. }
  611. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  612. return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
  613. }
  614. public IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
  615. {
  616. return GetFiles(path, null, false, recursive);
  617. }
  618. public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  619. {
  620. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  621. {
  622. return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive);
  623. }
  624. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  625. // On linux and osx the search pattern is case sensitive
  626. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  627. if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
  628. {
  629. return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
  630. }
  631. var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
  632. if (extensions != null && extensions.Length > 0)
  633. {
  634. files = files.Where(i =>
  635. {
  636. var ext = i.Extension;
  637. if (ext == null)
  638. {
  639. return false;
  640. }
  641. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  642. });
  643. }
  644. return ToMetadata(files);
  645. }
  646. public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  647. {
  648. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  649. {
  650. return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive);
  651. }
  652. var directoryInfo = new DirectoryInfo(path);
  653. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  654. if (EnableFileSystemRequestConcat)
  655. {
  656. return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
  657. .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
  658. }
  659. return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", searchOption));
  660. }
  661. private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
  662. {
  663. return infos.Select(GetFileSystemMetadata);
  664. }
  665. public string[] ReadAllLines(string path)
  666. {
  667. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  668. {
  669. return _sharpCifsFileSystem.ReadAllLines(path);
  670. }
  671. return File.ReadAllLines(path);
  672. }
  673. public void WriteAllLines(string path, IEnumerable<string> lines)
  674. {
  675. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  676. {
  677. _sharpCifsFileSystem.WriteAllLines(path, lines);
  678. return;
  679. }
  680. File.WriteAllLines(path, lines);
  681. }
  682. public Stream OpenRead(string path)
  683. {
  684. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  685. {
  686. return _sharpCifsFileSystem.OpenRead(path);
  687. }
  688. return File.OpenRead(path);
  689. }
  690. public void CopyFile(string source, string target, bool overwrite)
  691. {
  692. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  693. {
  694. _sharpCifsFileSystem.CopyFile(source, target, overwrite);
  695. return;
  696. }
  697. File.Copy(source, target, overwrite);
  698. }
  699. public void MoveFile(string source, string target)
  700. {
  701. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  702. {
  703. _sharpCifsFileSystem.MoveFile(source, target);
  704. return;
  705. }
  706. File.Move(source, target);
  707. }
  708. public void MoveDirectory(string source, string target)
  709. {
  710. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  711. {
  712. _sharpCifsFileSystem.MoveDirectory(source, target);
  713. return;
  714. }
  715. Directory.Move(source, target);
  716. }
  717. public bool DirectoryExists(string path)
  718. {
  719. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  720. {
  721. return _sharpCifsFileSystem.DirectoryExists(path);
  722. }
  723. return Directory.Exists(path);
  724. }
  725. public bool FileExists(string path)
  726. {
  727. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  728. {
  729. return _sharpCifsFileSystem.FileExists(path);
  730. }
  731. return File.Exists(path);
  732. }
  733. public string ReadAllText(string path)
  734. {
  735. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  736. {
  737. return _sharpCifsFileSystem.ReadAllText(path);
  738. }
  739. return File.ReadAllText(path);
  740. }
  741. public byte[] ReadAllBytes(string path)
  742. {
  743. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  744. {
  745. return _sharpCifsFileSystem.ReadAllBytes(path);
  746. }
  747. return File.ReadAllBytes(path);
  748. }
  749. public void WriteAllText(string path, string text, Encoding encoding)
  750. {
  751. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  752. {
  753. _sharpCifsFileSystem.WriteAllText(path, text, encoding);
  754. return;
  755. }
  756. File.WriteAllText(path, text, encoding);
  757. }
  758. public void WriteAllText(string path, string text)
  759. {
  760. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  761. {
  762. _sharpCifsFileSystem.WriteAllText(path, text);
  763. return;
  764. }
  765. File.WriteAllText(path, text);
  766. }
  767. public void WriteAllBytes(string path, byte[] bytes)
  768. {
  769. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  770. {
  771. _sharpCifsFileSystem.WriteAllBytes(path, bytes);
  772. return;
  773. }
  774. File.WriteAllBytes(path, bytes);
  775. }
  776. public string ReadAllText(string path, Encoding encoding)
  777. {
  778. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  779. {
  780. return _sharpCifsFileSystem.ReadAllText(path, encoding);
  781. }
  782. return File.ReadAllText(path, encoding);
  783. }
  784. public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  785. {
  786. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  787. {
  788. return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive);
  789. }
  790. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  791. return Directory.EnumerateDirectories(path, "*", searchOption);
  792. }
  793. public IEnumerable<string> GetFilePaths(string path, bool recursive = false)
  794. {
  795. return GetFilePaths(path, null, false, recursive);
  796. }
  797. public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  798. {
  799. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  800. {
  801. return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive);
  802. }
  803. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  804. // On linux and osx the search pattern is case sensitive
  805. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  806. if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
  807. {
  808. return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
  809. }
  810. var files = Directory.EnumerateFiles(path, "*", searchOption);
  811. if (extensions != null && extensions.Length > 0)
  812. {
  813. files = files.Where(i =>
  814. {
  815. var ext = Path.GetExtension(i);
  816. if (ext == null)
  817. {
  818. return false;
  819. }
  820. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  821. });
  822. }
  823. return files;
  824. }
  825. public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  826. {
  827. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  828. {
  829. return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive);
  830. }
  831. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  832. return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
  833. }
  834. public virtual void SetExecutable(string path)
  835. {
  836. }
  837. }
  838. }