FileSystem.cs 12 KB

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