CommonFileSystem.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Model.Logging;
  4. using System;
  5. using System.IO;
  6. using System.Text;
  7. namespace MediaBrowser.Common.Implementations.IO
  8. {
  9. /// <summary>
  10. /// Class CommonFileSystem
  11. /// </summary>
  12. public class CommonFileSystem : IFileSystem
  13. {
  14. protected ILogger Logger;
  15. private readonly bool _supportsAsyncFileStreams;
  16. private char[] _invalidFileNameChars;
  17. public CommonFileSystem(ILogger logger, bool supportsAsyncFileStreams, bool usePresetInvalidFileNameChars)
  18. {
  19. Logger = logger;
  20. _supportsAsyncFileStreams = supportsAsyncFileStreams;
  21. SetInvalidFileNameChars(usePresetInvalidFileNameChars);
  22. }
  23. private void SetInvalidFileNameChars(bool usePresetInvalidFileNameChars)
  24. {
  25. // GetInvalidFileNameChars is less restrictive in Linux/Mac than Windows, this mimic Windows behavior for mono under Linux/Mac.
  26. if (usePresetInvalidFileNameChars)
  27. {
  28. _invalidFileNameChars = new char[41] { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  29. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  30. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  31. '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' };
  32. }
  33. else
  34. {
  35. _invalidFileNameChars = Path.GetInvalidFileNameChars();
  36. }
  37. }
  38. /// <summary>
  39. /// Determines whether the specified filename is shortcut.
  40. /// </summary>
  41. /// <param name="filename">The filename.</param>
  42. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  43. /// <exception cref="System.ArgumentNullException">filename</exception>
  44. public virtual bool IsShortcut(string filename)
  45. {
  46. if (string.IsNullOrEmpty(filename))
  47. {
  48. throw new ArgumentNullException("filename");
  49. }
  50. var extension = Path.GetExtension(filename);
  51. return string.Equals(extension, ".mblink", StringComparison.OrdinalIgnoreCase);
  52. }
  53. /// <summary>
  54. /// Resolves the shortcut.
  55. /// </summary>
  56. /// <param name="filename">The filename.</param>
  57. /// <returns>System.String.</returns>
  58. /// <exception cref="System.ArgumentNullException">filename</exception>
  59. public virtual string ResolveShortcut(string filename)
  60. {
  61. if (string.IsNullOrEmpty(filename))
  62. {
  63. throw new ArgumentNullException("filename");
  64. }
  65. if (string.Equals(Path.GetExtension(filename), ".mblink", StringComparison.OrdinalIgnoreCase))
  66. {
  67. var path = File.ReadAllText(filename);
  68. return NormalizePath(path);
  69. }
  70. return null;
  71. }
  72. /// <summary>
  73. /// Creates the shortcut.
  74. /// </summary>
  75. /// <param name="shortcutPath">The shortcut path.</param>
  76. /// <param name="target">The target.</param>
  77. /// <exception cref="System.ArgumentNullException">
  78. /// shortcutPath
  79. /// or
  80. /// target
  81. /// </exception>
  82. public void CreateShortcut(string shortcutPath, string target)
  83. {
  84. if (string.IsNullOrEmpty(shortcutPath))
  85. {
  86. throw new ArgumentNullException("shortcutPath");
  87. }
  88. if (string.IsNullOrEmpty(target))
  89. {
  90. throw new ArgumentNullException("target");
  91. }
  92. File.WriteAllText(shortcutPath, target);
  93. }
  94. /// <summary>
  95. /// Gets the file system info.
  96. /// </summary>
  97. /// <param name="path">The path.</param>
  98. /// <returns>FileSystemInfo.</returns>
  99. public FileSystemInfo GetFileSystemInfo(string path)
  100. {
  101. if (string.IsNullOrEmpty(path))
  102. {
  103. throw new ArgumentNullException("path");
  104. }
  105. // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
  106. if (Path.HasExtension(path))
  107. {
  108. var fileInfo = new FileInfo(path);
  109. if (fileInfo.Exists)
  110. {
  111. return fileInfo;
  112. }
  113. return new DirectoryInfo(path);
  114. }
  115. else
  116. {
  117. var fileInfo = new DirectoryInfo(path);
  118. if (fileInfo.Exists)
  119. {
  120. return fileInfo;
  121. }
  122. return new FileInfo(path);
  123. }
  124. }
  125. /// <summary>
  126. /// The space char
  127. /// </summary>
  128. private const char SpaceChar = ' ';
  129. /// <summary>
  130. /// Takes a filename and removes invalid characters
  131. /// </summary>
  132. /// <param name="filename">The filename.</param>
  133. /// <returns>System.String.</returns>
  134. /// <exception cref="System.ArgumentNullException">filename</exception>
  135. public string GetValidFilename(string filename)
  136. {
  137. if (string.IsNullOrEmpty(filename))
  138. {
  139. throw new ArgumentNullException("filename");
  140. }
  141. var builder = new StringBuilder(filename);
  142. foreach (var c in _invalidFileNameChars)
  143. {
  144. builder = builder.Replace(c, SpaceChar);
  145. }
  146. return builder.ToString();
  147. }
  148. /// <summary>
  149. /// Gets the creation time UTC.
  150. /// </summary>
  151. /// <param name="info">The info.</param>
  152. /// <returns>DateTime.</returns>
  153. public DateTime GetCreationTimeUtc(FileSystemInfo info)
  154. {
  155. // This could throw an error on some file systems that have dates out of range
  156. try
  157. {
  158. return info.CreationTimeUtc;
  159. }
  160. catch (Exception ex)
  161. {
  162. Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName);
  163. return DateTime.MinValue;
  164. }
  165. }
  166. /// <summary>
  167. /// Gets the creation time UTC.
  168. /// </summary>
  169. /// <param name="info">The info.</param>
  170. /// <returns>DateTime.</returns>
  171. public DateTime GetLastWriteTimeUtc(FileSystemInfo info)
  172. {
  173. // This could throw an error on some file systems that have dates out of range
  174. try
  175. {
  176. return info.LastWriteTimeUtc;
  177. }
  178. catch (Exception ex)
  179. {
  180. Logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName);
  181. return DateTime.MinValue;
  182. }
  183. }
  184. /// <summary>
  185. /// Gets the last write time UTC.
  186. /// </summary>
  187. /// <param name="path">The path.</param>
  188. /// <returns>DateTime.</returns>
  189. public DateTime GetLastWriteTimeUtc(string path)
  190. {
  191. return GetLastWriteTimeUtc(GetFileSystemInfo(path));
  192. }
  193. /// <summary>
  194. /// Gets the file stream.
  195. /// </summary>
  196. /// <param name="path">The path.</param>
  197. /// <param name="mode">The mode.</param>
  198. /// <param name="access">The access.</param>
  199. /// <param name="share">The share.</param>
  200. /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
  201. /// <returns>FileStream.</returns>
  202. public FileStream GetFileStream(string path, FileMode mode, FileAccess access, FileShare share, bool isAsync = false)
  203. {
  204. if (_supportsAsyncFileStreams && isAsync)
  205. {
  206. return new FileStream(path, mode, access, share, 4096, true);
  207. }
  208. return new FileStream(path, mode, access, share);
  209. }
  210. /// <summary>
  211. /// Swaps the files.
  212. /// </summary>
  213. /// <param name="file1">The file1.</param>
  214. /// <param name="file2">The file2.</param>
  215. public void SwapFiles(string file1, string file2)
  216. {
  217. if (string.IsNullOrEmpty(file1))
  218. {
  219. throw new ArgumentNullException("file1");
  220. }
  221. if (string.IsNullOrEmpty(file2))
  222. {
  223. throw new ArgumentNullException("file2");
  224. }
  225. var temp1 = Path.GetTempFileName();
  226. var temp2 = Path.GetTempFileName();
  227. // Copying over will fail against hidden files
  228. RemoveHiddenAttribute(file1);
  229. RemoveHiddenAttribute(file2);
  230. File.Copy(file1, temp1, true);
  231. File.Copy(file2, temp2, true);
  232. File.Copy(temp1, file2, true);
  233. File.Copy(temp2, file1, true);
  234. DeleteFile(temp1);
  235. DeleteFile(temp2);
  236. }
  237. /// <summary>
  238. /// Removes the hidden attribute.
  239. /// </summary>
  240. /// <param name="path">The path.</param>
  241. private void RemoveHiddenAttribute(string path)
  242. {
  243. if (string.IsNullOrEmpty(path))
  244. {
  245. throw new ArgumentNullException("path");
  246. }
  247. var currentFile = new FileInfo(path);
  248. // This will fail if the file is hidden
  249. if (currentFile.Exists)
  250. {
  251. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  252. {
  253. currentFile.Attributes &= ~FileAttributes.Hidden;
  254. }
  255. }
  256. }
  257. public bool ContainsSubPath(string parentPath, string path)
  258. {
  259. if (string.IsNullOrEmpty(parentPath))
  260. {
  261. throw new ArgumentNullException("parentPath");
  262. }
  263. if (string.IsNullOrEmpty(path))
  264. {
  265. throw new ArgumentNullException("path");
  266. }
  267. return path.IndexOf(parentPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  268. }
  269. public bool IsRootPath(string path)
  270. {
  271. if (string.IsNullOrEmpty(path))
  272. {
  273. throw new ArgumentNullException("path");
  274. }
  275. var parent = Path.GetDirectoryName(path);
  276. if (!string.IsNullOrEmpty(parent))
  277. {
  278. return false;
  279. }
  280. return true;
  281. }
  282. public string NormalizePath(string path)
  283. {
  284. if (string.IsNullOrEmpty(path))
  285. {
  286. throw new ArgumentNullException("path");
  287. }
  288. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  289. {
  290. return path;
  291. }
  292. return path.TrimEnd(Path.DirectorySeparatorChar);
  293. }
  294. public string SubstitutePath(string path, string from, string to)
  295. {
  296. if (string.IsNullOrWhiteSpace(path))
  297. {
  298. throw new ArgumentNullException("path");
  299. }
  300. if (string.IsNullOrWhiteSpace(from))
  301. {
  302. throw new ArgumentNullException("from");
  303. }
  304. if (string.IsNullOrWhiteSpace(to))
  305. {
  306. throw new ArgumentNullException("to");
  307. }
  308. var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
  309. if (!string.Equals(newPath, path))
  310. {
  311. if (to.IndexOf('/') != -1)
  312. {
  313. newPath = newPath.Replace('\\', '/');
  314. }
  315. else
  316. {
  317. newPath = newPath.Replace('/', '\\');
  318. }
  319. }
  320. return newPath;
  321. }
  322. public string GetFileNameWithoutExtension(FileSystemInfo info)
  323. {
  324. if (info is DirectoryInfo)
  325. {
  326. return info.Name;
  327. }
  328. return Path.GetFileNameWithoutExtension(info.FullName);
  329. }
  330. public string GetFileNameWithoutExtension(string path)
  331. {
  332. return Path.GetFileNameWithoutExtension(path);
  333. }
  334. public bool IsPathFile(string path)
  335. {
  336. if (string.IsNullOrWhiteSpace(path))
  337. {
  338. throw new ArgumentNullException("path");
  339. }
  340. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  341. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  342. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  343. {
  344. return false;
  345. }
  346. return true;
  347. //return Path.IsPathRooted(path);
  348. }
  349. public void DeleteFile(string path, bool sendToRecycleBin)
  350. {
  351. File.Delete(path);
  352. }
  353. public void DeleteDirectory(string path, bool recursive, bool sendToRecycleBin)
  354. {
  355. Directory.Delete(path, recursive);
  356. }
  357. public void DeleteFile(string path)
  358. {
  359. DeleteFile(path, false);
  360. }
  361. public void DeleteDirectory(string path, bool recursive)
  362. {
  363. DeleteDirectory(path, recursive, false);
  364. }
  365. }
  366. }