FileSystem.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using MediaBrowser.Model.Logging;
  4. using System;
  5. using System.Collections.Specialized;
  6. using System.IO;
  7. using System.Text;
  8. namespace MediaBrowser.Controller.IO
  9. {
  10. /// <summary>
  11. /// Class FileSystem
  12. /// </summary>
  13. public static class FileSystem
  14. {
  15. /// <summary>
  16. /// Gets the file system info.
  17. /// </summary>
  18. /// <param name="path">The path.</param>
  19. /// <returns>FileSystemInfo.</returns>
  20. public static FileSystemInfo GetFileSystemInfo(string path)
  21. {
  22. // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
  23. if (Path.HasExtension(path))
  24. {
  25. var fileInfo = new FileInfo(path);
  26. if (fileInfo.Exists)
  27. {
  28. return fileInfo;
  29. }
  30. return new DirectoryInfo(path);
  31. }
  32. else
  33. {
  34. var fileInfo = new DirectoryInfo(path);
  35. if (fileInfo.Exists)
  36. {
  37. return fileInfo;
  38. }
  39. return new FileInfo(path);
  40. }
  41. }
  42. /// <summary>
  43. /// Gets the creation time UTC.
  44. /// </summary>
  45. /// <param name="info">The info.</param>
  46. /// <param name="logger">The logger.</param>
  47. /// <returns>DateTime.</returns>
  48. public static DateTime GetLastWriteTimeUtc(FileSystemInfo info, ILogger logger)
  49. {
  50. // This could throw an error on some file systems that have dates out of range
  51. try
  52. {
  53. return info.LastWriteTimeUtc;
  54. }
  55. catch (Exception ex)
  56. {
  57. logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName);
  58. return DateTime.MinValue;
  59. }
  60. }
  61. /// <summary>
  62. /// Gets the creation time UTC.
  63. /// </summary>
  64. /// <param name="info">The info.</param>
  65. /// <param name="logger">The logger.</param>
  66. /// <returns>DateTime.</returns>
  67. public static DateTime GetCreationTimeUtc(FileSystemInfo info, ILogger logger)
  68. {
  69. // This could throw an error on some file systems that have dates out of range
  70. try
  71. {
  72. return info.CreationTimeUtc;
  73. }
  74. catch (Exception ex)
  75. {
  76. logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName);
  77. return DateTime.MinValue;
  78. }
  79. }
  80. /// <summary>
  81. /// The space char
  82. /// </summary>
  83. private const char SpaceChar = ' ';
  84. /// <summary>
  85. /// The invalid file name chars
  86. /// </summary>
  87. private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();
  88. /// <summary>
  89. /// Takes a filename and removes invalid characters
  90. /// </summary>
  91. /// <param name="filename">The filename.</param>
  92. /// <returns>System.String.</returns>
  93. /// <exception cref="System.ArgumentNullException">filename</exception>
  94. public static string GetValidFilename(string filename)
  95. {
  96. if (string.IsNullOrEmpty(filename))
  97. {
  98. throw new ArgumentNullException("filename");
  99. }
  100. var builder = new StringBuilder(filename);
  101. foreach (var c in InvalidFileNameChars)
  102. {
  103. builder = builder.Replace(c, SpaceChar);
  104. }
  105. return builder.ToString();
  106. }
  107. /// <summary>
  108. /// Resolves the shortcut.
  109. /// </summary>
  110. /// <param name="filename">The filename.</param>
  111. /// <returns>System.String.</returns>
  112. /// <exception cref="System.ArgumentNullException">filename</exception>
  113. public static string ResolveShortcut(string filename)
  114. {
  115. if (string.IsNullOrEmpty(filename))
  116. {
  117. throw new ArgumentNullException("filename");
  118. }
  119. if (string.Equals(Path.GetExtension(filename), ".mblink", StringComparison.OrdinalIgnoreCase))
  120. {
  121. return File.ReadAllText(filename);
  122. }
  123. //return new WindowsShortcut(filename).ResolvedPath;
  124. var link = new ShellLink();
  125. ((IPersistFile)link).Load(filename, NativeMethods.STGM_READ);
  126. // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
  127. // ((IShellLinkW)link).Resolve(hwnd, 0)
  128. var sb = new StringBuilder(NativeMethods.MAX_PATH);
  129. WIN32_FIND_DATA data;
  130. ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
  131. return sb.ToString();
  132. }
  133. /// <summary>
  134. /// Creates a shortcut file pointing to a specified path
  135. /// </summary>
  136. /// <param name="shortcutPath">The shortcut path.</param>
  137. /// <param name="target">The target.</param>
  138. /// <exception cref="System.ArgumentNullException">shortcutPath</exception>
  139. public static void CreateShortcut(string shortcutPath, string target)
  140. {
  141. if (string.IsNullOrEmpty(shortcutPath))
  142. {
  143. throw new ArgumentNullException("shortcutPath");
  144. }
  145. if (string.IsNullOrEmpty(target))
  146. {
  147. throw new ArgumentNullException("target");
  148. }
  149. File.WriteAllText(shortcutPath, target);
  150. //var link = new ShellLink();
  151. //((IShellLinkW)link).SetPath(target);
  152. //((IPersistFile)link).Save(shortcutPath, true);
  153. }
  154. private static readonly Dictionary<string, string> ShortcutExtensionsDictionary = new[] { ".mblink", ".lnk" }
  155. .ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  156. /// <summary>
  157. /// Determines whether the specified filename is shortcut.
  158. /// </summary>
  159. /// <param name="filename">The filename.</param>
  160. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  161. /// <exception cref="System.ArgumentNullException">filename</exception>
  162. public static bool IsShortcut(string filename)
  163. {
  164. if (string.IsNullOrEmpty(filename))
  165. {
  166. throw new ArgumentNullException("filename");
  167. }
  168. var extension = Path.GetExtension(filename);
  169. return !string.IsNullOrEmpty(extension) && ShortcutExtensionsDictionary.ContainsKey(extension);
  170. }
  171. /// <summary>
  172. /// Copies all.
  173. /// </summary>
  174. /// <param name="source">The source.</param>
  175. /// <param name="target">The target.</param>
  176. /// <exception cref="System.ArgumentNullException">source</exception>
  177. /// <exception cref="System.ArgumentException">The source and target directories are the same</exception>
  178. public static void CopyAll(string source, string target)
  179. {
  180. if (string.IsNullOrEmpty(source))
  181. {
  182. throw new ArgumentNullException("source");
  183. }
  184. if (string.IsNullOrEmpty(target))
  185. {
  186. throw new ArgumentNullException("target");
  187. }
  188. if (source.Equals(target, StringComparison.OrdinalIgnoreCase))
  189. {
  190. throw new ArgumentException("The source and target directories are the same");
  191. }
  192. // Check if the target directory exists, if not, create it.
  193. Directory.CreateDirectory(target);
  194. foreach (var file in Directory.EnumerateFiles(source))
  195. {
  196. File.Copy(file, Path.Combine(target, Path.GetFileName(file)), true);
  197. }
  198. // Copy each subdirectory using recursion.
  199. foreach (var dir in Directory.EnumerateDirectories(source))
  200. {
  201. CopyAll(dir, Path.Combine(target, Path.GetFileName(dir)));
  202. }
  203. }
  204. /// <summary>
  205. /// Parses the ini file.
  206. /// </summary>
  207. /// <param name="path">The path.</param>
  208. /// <returns>NameValueCollection.</returns>
  209. public static NameValueCollection ParseIniFile(string path)
  210. {
  211. var values = new NameValueCollection();
  212. foreach (var line in File.ReadAllLines(path))
  213. {
  214. var data = line.Split('=');
  215. if (data.Length < 2) continue;
  216. var key = data[0];
  217. var value = data.Length == 2 ? data[1] : string.Join(string.Empty, data, 1, data.Length - 1);
  218. values[key] = value;
  219. }
  220. return values;
  221. }
  222. }
  223. /// <summary>
  224. /// Adapted from http://stackoverflow.com/questions/309495/windows-shortcut-lnk-parser-in-java
  225. /// </summary>
  226. internal class WindowsShortcut
  227. {
  228. public bool IsDirectory { get; private set; }
  229. public bool IsLocal { get; private set; }
  230. public string ResolvedPath { get; private set; }
  231. public WindowsShortcut(string file)
  232. {
  233. ParseLink(File.ReadAllBytes(file), Encoding.UTF8);
  234. }
  235. private static bool isMagicPresent(byte[] link)
  236. {
  237. const int magic = 0x0000004C;
  238. const int magic_offset = 0x00;
  239. return link.Length >= 32 && bytesToDword(link, magic_offset) == magic;
  240. }
  241. /**
  242. * Gobbles up link data by parsing it and storing info in member fields
  243. * @param link all the bytes from the .lnk file
  244. */
  245. private void ParseLink(byte[] link, Encoding encoding)
  246. {
  247. if (!isMagicPresent(link))
  248. throw new IOException("Invalid shortcut; magic is missing", 0);
  249. // get the flags byte
  250. byte flags = link[0x14];
  251. // get the file attributes byte
  252. const int file_atts_offset = 0x18;
  253. byte file_atts = link[file_atts_offset];
  254. byte is_dir_mask = (byte)0x10;
  255. if ((file_atts & is_dir_mask) > 0)
  256. {
  257. IsDirectory = true;
  258. }
  259. else
  260. {
  261. IsDirectory = false;
  262. }
  263. // if the shell settings are present, skip them
  264. const int shell_offset = 0x4c;
  265. const byte has_shell_mask = (byte)0x01;
  266. int shell_len = 0;
  267. if ((flags & has_shell_mask) > 0)
  268. {
  269. // the plus 2 accounts for the length marker itself
  270. shell_len = bytesToWord(link, shell_offset) + 2;
  271. }
  272. // get to the file settings
  273. int file_start = 0x4c + shell_len;
  274. const int file_location_info_flag_offset_offset = 0x08;
  275. int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];
  276. IsLocal = (file_location_info_flag & 2) == 0;
  277. // get the local volume and local system values
  278. //final int localVolumeTable_offset_offset = 0x0C;
  279. const int basename_offset_offset = 0x10;
  280. const int networkVolumeTable_offset_offset = 0x14;
  281. const int finalname_offset_offset = 0x18;
  282. int finalname_offset = link[file_start + finalname_offset_offset] + file_start;
  283. String finalname = getNullDelimitedString(link, finalname_offset, encoding);
  284. if (IsLocal)
  285. {
  286. int basename_offset = link[file_start + basename_offset_offset] + file_start;
  287. String basename = getNullDelimitedString(link, basename_offset, encoding);
  288. ResolvedPath = basename + finalname;
  289. }
  290. else
  291. {
  292. int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;
  293. int shareName_offset_offset = 0x08;
  294. int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]
  295. + networkVolumeTable_offset;
  296. String shareName = getNullDelimitedString(link, shareName_offset, encoding);
  297. ResolvedPath = shareName + "\\" + finalname;
  298. }
  299. }
  300. private static string getNullDelimitedString(byte[] bytes, int off, Encoding encoding)
  301. {
  302. int len = 0;
  303. // count bytes until the null character (0)
  304. while (true)
  305. {
  306. if (bytes[off + len] == 0)
  307. {
  308. break;
  309. }
  310. len++;
  311. }
  312. return encoding.GetString(bytes, off, len);
  313. }
  314. /*
  315. * convert two bytes into a short note, this is little endian because it's
  316. * for an Intel only OS.
  317. */
  318. private static int bytesToWord(byte[] bytes, int off)
  319. {
  320. return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
  321. }
  322. private static int bytesToDword(byte[] bytes, int off)
  323. {
  324. return (bytesToWord(bytes, off + 2) << 16) | bytesToWord(bytes, off);
  325. }
  326. }
  327. }