ManagedFileSystem.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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 GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous);
  340. }
  341. return GetFileStream(path, mode, access, share, FileOpenOptions.None);
  342. }
  343. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
  344. {
  345. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  346. {
  347. return _sharpCifsFileSystem.GetFileStream(path, mode, access, share);
  348. }
  349. var defaultBufferSize = 4096;
  350. return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions));
  351. }
  352. private FileOptions GetFileOptions(FileOpenOptions mode)
  353. {
  354. var val = (int)mode;
  355. return (FileOptions)val;
  356. }
  357. private FileMode GetFileMode(FileOpenMode mode)
  358. {
  359. switch (mode)
  360. {
  361. //case FileOpenMode.Append:
  362. // return FileMode.Append;
  363. case FileOpenMode.Create:
  364. return FileMode.Create;
  365. case FileOpenMode.CreateNew:
  366. return FileMode.CreateNew;
  367. case FileOpenMode.Open:
  368. return FileMode.Open;
  369. case FileOpenMode.OpenOrCreate:
  370. return FileMode.OpenOrCreate;
  371. //case FileOpenMode.Truncate:
  372. // return FileMode.Truncate;
  373. default:
  374. throw new Exception("Unrecognized FileOpenMode");
  375. }
  376. }
  377. private FileAccess GetFileAccess(FileAccessMode mode)
  378. {
  379. switch (mode)
  380. {
  381. //case FileAccessMode.ReadWrite:
  382. // return FileAccess.ReadWrite;
  383. case FileAccessMode.Write:
  384. return FileAccess.Write;
  385. case FileAccessMode.Read:
  386. return FileAccess.Read;
  387. default:
  388. throw new Exception("Unrecognized FileAccessMode");
  389. }
  390. }
  391. private FileShare GetFileShare(FileShareMode mode)
  392. {
  393. switch (mode)
  394. {
  395. case FileShareMode.ReadWrite:
  396. return FileShare.ReadWrite;
  397. case FileShareMode.Write:
  398. return FileShare.Write;
  399. case FileShareMode.Read:
  400. return FileShare.Read;
  401. case FileShareMode.None:
  402. return FileShare.None;
  403. default:
  404. throw new Exception("Unrecognized FileShareMode");
  405. }
  406. }
  407. public void SetHidden(string path, bool isHidden)
  408. {
  409. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  410. {
  411. _sharpCifsFileSystem.SetHidden(path, isHidden);
  412. return;
  413. }
  414. var info = GetFileInfo(path);
  415. if (info.Exists && info.IsHidden != isHidden)
  416. {
  417. if (isHidden)
  418. {
  419. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
  420. }
  421. else
  422. {
  423. FileAttributes attributes = File.GetAttributes(path);
  424. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  425. File.SetAttributes(path, attributes);
  426. }
  427. }
  428. }
  429. public void SetReadOnly(string path, bool isReadOnly)
  430. {
  431. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  432. {
  433. _sharpCifsFileSystem.SetReadOnly(path, isReadOnly);
  434. return;
  435. }
  436. var info = GetFileInfo(path);
  437. if (info.Exists && info.IsReadOnly != isReadOnly)
  438. {
  439. if (isReadOnly)
  440. {
  441. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
  442. }
  443. else
  444. {
  445. FileAttributes attributes = File.GetAttributes(path);
  446. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  447. File.SetAttributes(path, attributes);
  448. }
  449. }
  450. }
  451. public void SetAttributes(string path, bool isHidden, bool isReadOnly)
  452. {
  453. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  454. {
  455. _sharpCifsFileSystem.SetAttributes(path, isHidden, isReadOnly);
  456. return;
  457. }
  458. var info = GetFileInfo(path);
  459. if (!info.Exists)
  460. {
  461. return;
  462. }
  463. if (info.IsReadOnly == isReadOnly && info.IsHidden == isHidden)
  464. {
  465. return;
  466. }
  467. var attributes = File.GetAttributes(path);
  468. if (isReadOnly)
  469. {
  470. attributes = attributes | FileAttributes.ReadOnly;
  471. }
  472. else
  473. {
  474. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  475. }
  476. if (isHidden)
  477. {
  478. attributes = attributes | FileAttributes.Hidden;
  479. }
  480. else
  481. {
  482. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  483. }
  484. File.SetAttributes(path, attributes);
  485. }
  486. private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
  487. {
  488. return attributes & ~attributesToRemove;
  489. }
  490. /// <summary>
  491. /// Swaps the files.
  492. /// </summary>
  493. /// <param name="file1">The file1.</param>
  494. /// <param name="file2">The file2.</param>
  495. public void SwapFiles(string file1, string file2)
  496. {
  497. if (string.IsNullOrEmpty(file1))
  498. {
  499. throw new ArgumentNullException("file1");
  500. }
  501. if (string.IsNullOrEmpty(file2))
  502. {
  503. throw new ArgumentNullException("file2");
  504. }
  505. var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
  506. // Copying over will fail against hidden files
  507. SetHidden(file1, false);
  508. SetHidden(file2, false);
  509. Directory.CreateDirectory(_tempPath);
  510. CopyFile(file1, temp1, true);
  511. CopyFile(file2, file1, true);
  512. CopyFile(temp1, file2, true);
  513. }
  514. private char GetDirectorySeparatorChar(string path)
  515. {
  516. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  517. {
  518. return _sharpCifsFileSystem.GetDirectorySeparatorChar(path);
  519. }
  520. return Path.DirectorySeparatorChar;
  521. }
  522. public bool ContainsSubPath(string parentPath, string path)
  523. {
  524. if (string.IsNullOrEmpty(parentPath))
  525. {
  526. throw new ArgumentNullException("parentPath");
  527. }
  528. if (string.IsNullOrEmpty(path))
  529. {
  530. throw new ArgumentNullException("path");
  531. }
  532. var separatorChar = GetDirectorySeparatorChar(parentPath);
  533. return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  534. }
  535. public bool IsRootPath(string path)
  536. {
  537. if (string.IsNullOrEmpty(path))
  538. {
  539. throw new ArgumentNullException("path");
  540. }
  541. var parent = GetDirectoryName(path);
  542. if (!string.IsNullOrEmpty(parent))
  543. {
  544. return false;
  545. }
  546. return true;
  547. }
  548. public string GetDirectoryName(string path)
  549. {
  550. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  551. {
  552. return _sharpCifsFileSystem.GetDirectoryName(path);
  553. }
  554. return Path.GetDirectoryName(path);
  555. }
  556. public string NormalizePath(string path)
  557. {
  558. if (string.IsNullOrEmpty(path))
  559. {
  560. throw new ArgumentNullException("path");
  561. }
  562. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  563. {
  564. return _sharpCifsFileSystem.NormalizePath(path);
  565. }
  566. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  567. {
  568. return path;
  569. }
  570. return path.TrimEnd(GetDirectorySeparatorChar(path));
  571. }
  572. public bool AreEqual(string path1, string path2)
  573. {
  574. if (path1 == null && path2 == null)
  575. {
  576. return true;
  577. }
  578. if (path1 == null || path2 == null)
  579. {
  580. return false;
  581. }
  582. return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase);
  583. }
  584. public string GetFileNameWithoutExtension(FileSystemMetadata info)
  585. {
  586. if (info.IsDirectory)
  587. {
  588. return info.Name;
  589. }
  590. return Path.GetFileNameWithoutExtension(info.FullName);
  591. }
  592. public string GetFileNameWithoutExtension(string path)
  593. {
  594. return Path.GetFileNameWithoutExtension(path);
  595. }
  596. public bool IsPathFile(string path)
  597. {
  598. if (string.IsNullOrWhiteSpace(path))
  599. {
  600. throw new ArgumentNullException("path");
  601. }
  602. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  603. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  604. {
  605. return true;
  606. }
  607. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  608. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  609. {
  610. return false;
  611. }
  612. return true;
  613. //return Path.IsPathRooted(path);
  614. }
  615. public void DeleteFile(string path)
  616. {
  617. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  618. {
  619. _sharpCifsFileSystem.DeleteFile(path);
  620. return;
  621. }
  622. SetAttributes(path, false, false);
  623. File.Delete(path);
  624. }
  625. public void DeleteDirectory(string path, bool recursive)
  626. {
  627. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  628. {
  629. _sharpCifsFileSystem.DeleteDirectory(path, recursive);
  630. return;
  631. }
  632. Directory.Delete(path, recursive);
  633. }
  634. public void CreateDirectory(string path)
  635. {
  636. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  637. {
  638. _sharpCifsFileSystem.CreateDirectory(path);
  639. return;
  640. }
  641. Directory.CreateDirectory(path);
  642. }
  643. public List<FileSystemMetadata> GetDrives()
  644. {
  645. // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
  646. return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata
  647. {
  648. Name = GetName(d),
  649. FullName = d.RootDirectory.FullName,
  650. IsDirectory = true
  651. }).ToList();
  652. }
  653. private string GetName(DriveInfo drive)
  654. {
  655. return drive.Name;
  656. }
  657. public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  658. {
  659. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  660. {
  661. return _sharpCifsFileSystem.GetDirectories(path, recursive);
  662. }
  663. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  664. return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
  665. }
  666. public IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
  667. {
  668. return GetFiles(path, null, false, recursive);
  669. }
  670. public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  671. {
  672. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  673. {
  674. return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive);
  675. }
  676. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  677. // On linux and osx the search pattern is case sensitive
  678. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  679. if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
  680. {
  681. return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
  682. }
  683. var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
  684. if (extensions != null && extensions.Length > 0)
  685. {
  686. files = files.Where(i =>
  687. {
  688. var ext = i.Extension;
  689. if (ext == null)
  690. {
  691. return false;
  692. }
  693. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  694. });
  695. }
  696. return ToMetadata(files);
  697. }
  698. public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  699. {
  700. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  701. {
  702. return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive);
  703. }
  704. var directoryInfo = new DirectoryInfo(path);
  705. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  706. if (EnableFileSystemRequestConcat)
  707. {
  708. return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
  709. .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
  710. }
  711. return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", searchOption));
  712. }
  713. private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
  714. {
  715. return infos.Select(GetFileSystemMetadata);
  716. }
  717. public string[] ReadAllLines(string path)
  718. {
  719. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  720. {
  721. return _sharpCifsFileSystem.ReadAllLines(path);
  722. }
  723. return File.ReadAllLines(path);
  724. }
  725. public void WriteAllLines(string path, IEnumerable<string> lines)
  726. {
  727. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  728. {
  729. _sharpCifsFileSystem.WriteAllLines(path, lines);
  730. return;
  731. }
  732. File.WriteAllLines(path, lines);
  733. }
  734. public Stream OpenRead(string path)
  735. {
  736. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  737. {
  738. return _sharpCifsFileSystem.OpenRead(path);
  739. }
  740. return File.OpenRead(path);
  741. }
  742. public void CopyFile(string source, string target, bool overwrite)
  743. {
  744. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  745. {
  746. _sharpCifsFileSystem.CopyFile(source, target, overwrite);
  747. return;
  748. }
  749. File.Copy(source, target, overwrite);
  750. }
  751. public void MoveFile(string source, string target)
  752. {
  753. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  754. {
  755. _sharpCifsFileSystem.MoveFile(source, target);
  756. return;
  757. }
  758. File.Move(source, target);
  759. }
  760. public void MoveDirectory(string source, string target)
  761. {
  762. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  763. {
  764. _sharpCifsFileSystem.MoveDirectory(source, target);
  765. return;
  766. }
  767. Directory.Move(source, target);
  768. }
  769. public bool DirectoryExists(string path)
  770. {
  771. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  772. {
  773. return _sharpCifsFileSystem.DirectoryExists(path);
  774. }
  775. return Directory.Exists(path);
  776. }
  777. public bool FileExists(string path)
  778. {
  779. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  780. {
  781. return _sharpCifsFileSystem.FileExists(path);
  782. }
  783. return File.Exists(path);
  784. }
  785. public string ReadAllText(string path)
  786. {
  787. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  788. {
  789. return _sharpCifsFileSystem.ReadAllText(path);
  790. }
  791. return File.ReadAllText(path);
  792. }
  793. public byte[] ReadAllBytes(string path)
  794. {
  795. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  796. {
  797. return _sharpCifsFileSystem.ReadAllBytes(path);
  798. }
  799. return File.ReadAllBytes(path);
  800. }
  801. public void WriteAllText(string path, string text, Encoding encoding)
  802. {
  803. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  804. {
  805. _sharpCifsFileSystem.WriteAllText(path, text, encoding);
  806. return;
  807. }
  808. File.WriteAllText(path, text, encoding);
  809. }
  810. public void WriteAllText(string path, string text)
  811. {
  812. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  813. {
  814. _sharpCifsFileSystem.WriteAllText(path, text);
  815. return;
  816. }
  817. File.WriteAllText(path, text);
  818. }
  819. public void WriteAllBytes(string path, byte[] bytes)
  820. {
  821. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  822. {
  823. _sharpCifsFileSystem.WriteAllBytes(path, bytes);
  824. return;
  825. }
  826. File.WriteAllBytes(path, bytes);
  827. }
  828. public string ReadAllText(string path, Encoding encoding)
  829. {
  830. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  831. {
  832. return _sharpCifsFileSystem.ReadAllText(path, encoding);
  833. }
  834. return File.ReadAllText(path, encoding);
  835. }
  836. public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  837. {
  838. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  839. {
  840. return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive);
  841. }
  842. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  843. return Directory.EnumerateDirectories(path, "*", searchOption);
  844. }
  845. public IEnumerable<string> GetFilePaths(string path, bool recursive = false)
  846. {
  847. return GetFilePaths(path, null, false, recursive);
  848. }
  849. public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  850. {
  851. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  852. {
  853. return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive);
  854. }
  855. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  856. // On linux and osx the search pattern is case sensitive
  857. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  858. if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
  859. {
  860. return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
  861. }
  862. var files = Directory.EnumerateFiles(path, "*", searchOption);
  863. if (extensions != null && extensions.Length > 0)
  864. {
  865. files = files.Where(i =>
  866. {
  867. var ext = Path.GetExtension(i);
  868. if (ext == null)
  869. {
  870. return false;
  871. }
  872. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  873. });
  874. }
  875. return files;
  876. }
  877. public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  878. {
  879. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  880. {
  881. return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive);
  882. }
  883. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  884. return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
  885. }
  886. public virtual void SetExecutable(string path)
  887. {
  888. }
  889. }
  890. }