ManagedFileSystem.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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. private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
  452. {
  453. return attributes & ~attributesToRemove;
  454. }
  455. /// <summary>
  456. /// Swaps the files.
  457. /// </summary>
  458. /// <param name="file1">The file1.</param>
  459. /// <param name="file2">The file2.</param>
  460. public void SwapFiles(string file1, string file2)
  461. {
  462. if (string.IsNullOrEmpty(file1))
  463. {
  464. throw new ArgumentNullException("file1");
  465. }
  466. if (string.IsNullOrEmpty(file2))
  467. {
  468. throw new ArgumentNullException("file2");
  469. }
  470. var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
  471. // Copying over will fail against hidden files
  472. SetHidden(file1, false);
  473. SetHidden(file2, false);
  474. Directory.CreateDirectory(_tempPath);
  475. CopyFile(file1, temp1, true);
  476. CopyFile(file2, file1, true);
  477. CopyFile(temp1, file2, true);
  478. }
  479. private char GetDirectorySeparatorChar(string path)
  480. {
  481. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  482. {
  483. return _sharpCifsFileSystem.GetDirectorySeparatorChar(path);
  484. }
  485. return Path.DirectorySeparatorChar;
  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 = GetDirectoryName(path);
  507. if (!string.IsNullOrEmpty(parent))
  508. {
  509. return false;
  510. }
  511. return true;
  512. }
  513. public string GetDirectoryName(string path)
  514. {
  515. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  516. {
  517. return _sharpCifsFileSystem.GetDirectoryName(path);
  518. }
  519. return Path.GetDirectoryName(path);
  520. }
  521. public string NormalizePath(string path)
  522. {
  523. if (string.IsNullOrEmpty(path))
  524. {
  525. throw new ArgumentNullException("path");
  526. }
  527. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  528. {
  529. return _sharpCifsFileSystem.NormalizePath(path);
  530. }
  531. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  532. {
  533. return path;
  534. }
  535. return path.TrimEnd(GetDirectorySeparatorChar(path));
  536. }
  537. public bool AreEqual(string path1, string path2)
  538. {
  539. if (path1 == null && path2 == null)
  540. {
  541. return true;
  542. }
  543. if (path1 == null || path2 == null)
  544. {
  545. return false;
  546. }
  547. return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase);
  548. }
  549. public string GetFileNameWithoutExtension(FileSystemMetadata info)
  550. {
  551. if (info.IsDirectory)
  552. {
  553. return info.Name;
  554. }
  555. return Path.GetFileNameWithoutExtension(info.FullName);
  556. }
  557. public string GetFileNameWithoutExtension(string path)
  558. {
  559. return Path.GetFileNameWithoutExtension(path);
  560. }
  561. public bool IsPathFile(string path)
  562. {
  563. if (string.IsNullOrWhiteSpace(path))
  564. {
  565. throw new ArgumentNullException("path");
  566. }
  567. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  568. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  569. {
  570. return true;
  571. }
  572. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  573. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  574. {
  575. return false;
  576. }
  577. return true;
  578. //return Path.IsPathRooted(path);
  579. }
  580. public void DeleteFile(string path)
  581. {
  582. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  583. {
  584. _sharpCifsFileSystem.DeleteFile(path);
  585. return;
  586. }
  587. var fileInfo = GetFileInfo(path);
  588. if (fileInfo.Exists)
  589. {
  590. if (fileInfo.IsHidden)
  591. {
  592. SetHidden(path, false);
  593. }
  594. if (fileInfo.IsReadOnly)
  595. {
  596. SetReadOnly(path, false);
  597. }
  598. }
  599. File.Delete(path);
  600. }
  601. public void DeleteDirectory(string path, bool recursive)
  602. {
  603. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  604. {
  605. _sharpCifsFileSystem.DeleteDirectory(path, recursive);
  606. return;
  607. }
  608. Directory.Delete(path, recursive);
  609. }
  610. public void CreateDirectory(string path)
  611. {
  612. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  613. {
  614. _sharpCifsFileSystem.CreateDirectory(path);
  615. return;
  616. }
  617. Directory.CreateDirectory(path);
  618. }
  619. public List<FileSystemMetadata> GetDrives()
  620. {
  621. // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
  622. return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata
  623. {
  624. Name = GetName(d),
  625. FullName = d.RootDirectory.FullName,
  626. IsDirectory = true
  627. }).ToList();
  628. }
  629. private string GetName(DriveInfo drive)
  630. {
  631. return drive.Name;
  632. }
  633. public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  634. {
  635. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  636. {
  637. return _sharpCifsFileSystem.GetDirectories(path, recursive);
  638. }
  639. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  640. return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
  641. }
  642. public IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
  643. {
  644. return GetFiles(path, null, false, recursive);
  645. }
  646. public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  647. {
  648. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  649. {
  650. return _sharpCifsFileSystem.GetFiles(path, extensions, enableCaseSensitiveExtensions, recursive);
  651. }
  652. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  653. // On linux and osx the search pattern is case sensitive
  654. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  655. if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
  656. {
  657. return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
  658. }
  659. var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
  660. if (extensions != null && extensions.Length > 0)
  661. {
  662. files = files.Where(i =>
  663. {
  664. var ext = i.Extension;
  665. if (ext == null)
  666. {
  667. return false;
  668. }
  669. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  670. });
  671. }
  672. return ToMetadata(files);
  673. }
  674. public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  675. {
  676. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  677. {
  678. return _sharpCifsFileSystem.GetFileSystemEntries(path, recursive);
  679. }
  680. var directoryInfo = new DirectoryInfo(path);
  681. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  682. if (EnableFileSystemRequestConcat)
  683. {
  684. return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
  685. .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
  686. }
  687. return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", searchOption));
  688. }
  689. private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
  690. {
  691. return infos.Select(GetFileSystemMetadata);
  692. }
  693. public string[] ReadAllLines(string path)
  694. {
  695. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  696. {
  697. return _sharpCifsFileSystem.ReadAllLines(path);
  698. }
  699. return File.ReadAllLines(path);
  700. }
  701. public void WriteAllLines(string path, IEnumerable<string> lines)
  702. {
  703. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  704. {
  705. _sharpCifsFileSystem.WriteAllLines(path, lines);
  706. return;
  707. }
  708. File.WriteAllLines(path, lines);
  709. }
  710. public Stream OpenRead(string path)
  711. {
  712. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  713. {
  714. return _sharpCifsFileSystem.OpenRead(path);
  715. }
  716. return File.OpenRead(path);
  717. }
  718. public void CopyFile(string source, string target, bool overwrite)
  719. {
  720. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  721. {
  722. _sharpCifsFileSystem.CopyFile(source, target, overwrite);
  723. return;
  724. }
  725. File.Copy(source, target, overwrite);
  726. }
  727. public void MoveFile(string source, string target)
  728. {
  729. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  730. {
  731. _sharpCifsFileSystem.MoveFile(source, target);
  732. return;
  733. }
  734. File.Move(source, target);
  735. }
  736. public void MoveDirectory(string source, string target)
  737. {
  738. if (_sharpCifsFileSystem.IsEnabledForPath(source))
  739. {
  740. _sharpCifsFileSystem.MoveDirectory(source, target);
  741. return;
  742. }
  743. Directory.Move(source, target);
  744. }
  745. public bool DirectoryExists(string path)
  746. {
  747. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  748. {
  749. return _sharpCifsFileSystem.DirectoryExists(path);
  750. }
  751. return Directory.Exists(path);
  752. }
  753. public bool FileExists(string path)
  754. {
  755. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  756. {
  757. return _sharpCifsFileSystem.FileExists(path);
  758. }
  759. return File.Exists(path);
  760. }
  761. public string ReadAllText(string path)
  762. {
  763. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  764. {
  765. return _sharpCifsFileSystem.ReadAllText(path);
  766. }
  767. return File.ReadAllText(path);
  768. }
  769. public byte[] ReadAllBytes(string path)
  770. {
  771. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  772. {
  773. return _sharpCifsFileSystem.ReadAllBytes(path);
  774. }
  775. return File.ReadAllBytes(path);
  776. }
  777. public void WriteAllText(string path, string text, Encoding encoding)
  778. {
  779. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  780. {
  781. _sharpCifsFileSystem.WriteAllText(path, text, encoding);
  782. return;
  783. }
  784. File.WriteAllText(path, text, encoding);
  785. }
  786. public void WriteAllText(string path, string text)
  787. {
  788. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  789. {
  790. _sharpCifsFileSystem.WriteAllText(path, text);
  791. return;
  792. }
  793. File.WriteAllText(path, text);
  794. }
  795. public void WriteAllBytes(string path, byte[] bytes)
  796. {
  797. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  798. {
  799. _sharpCifsFileSystem.WriteAllBytes(path, bytes);
  800. return;
  801. }
  802. File.WriteAllBytes(path, bytes);
  803. }
  804. public string ReadAllText(string path, Encoding encoding)
  805. {
  806. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  807. {
  808. return _sharpCifsFileSystem.ReadAllText(path, encoding);
  809. }
  810. return File.ReadAllText(path, encoding);
  811. }
  812. public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  813. {
  814. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  815. {
  816. return _sharpCifsFileSystem.GetDirectoryPaths(path, recursive);
  817. }
  818. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  819. return Directory.EnumerateDirectories(path, "*", searchOption);
  820. }
  821. public IEnumerable<string> GetFilePaths(string path, bool recursive = false)
  822. {
  823. return GetFilePaths(path, null, false, recursive);
  824. }
  825. public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  826. {
  827. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  828. {
  829. return _sharpCifsFileSystem.GetFilePaths(path, extensions, enableCaseSensitiveExtensions, recursive);
  830. }
  831. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  832. // On linux and osx the search pattern is case sensitive
  833. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  834. if (enableCaseSensitiveExtensions && extensions != null && extensions.Length == 1)
  835. {
  836. return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
  837. }
  838. var files = Directory.EnumerateFiles(path, "*", searchOption);
  839. if (extensions != null && extensions.Length > 0)
  840. {
  841. files = files.Where(i =>
  842. {
  843. var ext = Path.GetExtension(i);
  844. if (ext == null)
  845. {
  846. return false;
  847. }
  848. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  849. });
  850. }
  851. return files;
  852. }
  853. public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  854. {
  855. if (_sharpCifsFileSystem.IsEnabledForPath(path))
  856. {
  857. return _sharpCifsFileSystem.GetFileSystemEntryPaths(path, recursive);
  858. }
  859. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  860. return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
  861. }
  862. public virtual void SetExecutable(string path)
  863. {
  864. }
  865. }
  866. }