CommonFileSystem.cs 12 KB

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