CommonFileSystem.cs 11 KB

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