2
0

FileSystem.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. using MediaBrowser.Common.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  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 information about a path
  17. /// </summary>
  18. /// <param name="path">The path.</param>
  19. /// <returns>System.Nullable{WIN32_FIND_DATA}.</returns>
  20. /// <exception cref="System.ArgumentNullException">path</exception>
  21. /// <exception cref="System.IO.IOException">GetFileData failed for + path</exception>
  22. public static WIN32_FIND_DATA? GetFileData(string path)
  23. {
  24. if (string.IsNullOrEmpty(path))
  25. {
  26. throw new ArgumentNullException("path");
  27. }
  28. WIN32_FIND_DATA data;
  29. var handle = NativeMethods.FindFirstFileEx(path, FINDEX_INFO_LEVELS.FindExInfoBasic, out data,
  30. FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FindFirstFileExFlags.NONE);
  31. var getFilename = false;
  32. if (handle == NativeMethods.INVALID_HANDLE_VALUE && !Path.HasExtension(path))
  33. {
  34. if (!path.EndsWith("*", StringComparison.OrdinalIgnoreCase))
  35. {
  36. NativeMethods.FindClose(handle);
  37. handle = NativeMethods.FindFirstFileEx(Path.Combine(path, "*"), FINDEX_INFO_LEVELS.FindExInfoBasic, out data,
  38. FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FindFirstFileExFlags.NONE);
  39. getFilename = true;
  40. }
  41. }
  42. if (handle == IntPtr.Zero)
  43. {
  44. throw new IOException("GetFileData failed for " + path);
  45. }
  46. NativeMethods.FindClose(handle);
  47. // According to MSDN documentation, this will default to 1601 for paths that don't exist.
  48. if (data.CreationTimeUtc.Year == 1601)
  49. {
  50. return null;
  51. }
  52. if (getFilename)
  53. {
  54. data.cFileName = Path.GetFileName(path);
  55. }
  56. data.Path = path;
  57. return data;
  58. }
  59. /// <summary>
  60. /// Gets all files within a folder
  61. /// </summary>
  62. /// <param name="path">The path.</param>
  63. /// <param name="searchPattern">The search pattern.</param>
  64. /// <returns>IEnumerable{WIN32_FIND_DATA}.</returns>
  65. public static IEnumerable<WIN32_FIND_DATA> GetFiles(string path, string searchPattern = "*")
  66. {
  67. return GetFileSystemEntries(path, searchPattern, includeDirectories: false);
  68. }
  69. /// <summary>
  70. /// Gets all sub-directories within a folder
  71. /// </summary>
  72. /// <param name="path">The path.</param>
  73. /// <returns>IEnumerable{WIN32_FIND_DATA}.</returns>
  74. public static IEnumerable<WIN32_FIND_DATA> GetDirectories(string path)
  75. {
  76. return GetFileSystemEntries(path, includeFiles: false);
  77. }
  78. /// <summary>
  79. /// Gets all file system entries within a foler
  80. /// </summary>
  81. /// <param name="path">The path.</param>
  82. /// <param name="searchPattern">The search pattern.</param>
  83. /// <param name="includeFiles">if set to <c>true</c> [include files].</param>
  84. /// <param name="includeDirectories">if set to <c>true</c> [include directories].</param>
  85. /// <returns>IEnumerable{WIN32_FIND_DATA}.</returns>
  86. /// <exception cref="System.ArgumentNullException">path</exception>
  87. /// <exception cref="System.IO.IOException">GetFileSystemEntries failed</exception>
  88. public static IEnumerable<WIN32_FIND_DATA> GetFileSystemEntries(string path, string searchPattern = "*", bool includeFiles = true, bool includeDirectories = true)
  89. {
  90. if (string.IsNullOrEmpty(path))
  91. {
  92. throw new ArgumentNullException("path");
  93. }
  94. var lpFileName = Path.Combine(path, searchPattern);
  95. WIN32_FIND_DATA lpFindFileData;
  96. var handle = NativeMethods.FindFirstFileEx(lpFileName, FINDEX_INFO_LEVELS.FindExInfoBasic, out lpFindFileData,
  97. FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FindFirstFileExFlags.FIND_FIRST_EX_LARGE_FETCH);
  98. if (handle == IntPtr.Zero)
  99. {
  100. var hr = Marshal.GetLastWin32Error();
  101. if (hr != 2 && hr != 0x12)
  102. {
  103. throw new IOException("GetFileSystemEntries failed");
  104. }
  105. yield break;
  106. }
  107. if (IncludeInFindFileOutput(lpFindFileData.cFileName, lpFindFileData.dwFileAttributes, includeFiles, includeDirectories))
  108. {
  109. lpFindFileData.Path = Path.Combine(path, lpFindFileData.cFileName);
  110. yield return lpFindFileData;
  111. }
  112. while (NativeMethods.FindNextFile(handle, out lpFindFileData) != IntPtr.Zero)
  113. {
  114. if (IncludeInFindFileOutput(lpFindFileData.cFileName, lpFindFileData.dwFileAttributes, includeFiles, includeDirectories))
  115. {
  116. lpFindFileData.Path = Path.Combine(path, lpFindFileData.cFileName);
  117. yield return lpFindFileData;
  118. }
  119. }
  120. NativeMethods.FindClose(handle);
  121. }
  122. /// <summary>
  123. /// Includes the in find file output.
  124. /// </summary>
  125. /// <param name="cFileName">Name of the c file.</param>
  126. /// <param name="attributes">The attributes.</param>
  127. /// <param name="includeFiles">if set to <c>true</c> [include files].</param>
  128. /// <param name="includeDirectories">if set to <c>true</c> [include directories].</param>
  129. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  130. public static bool IncludeInFindFileOutput(string cFileName, FileAttributes attributes, bool includeFiles, bool includeDirectories)
  131. {
  132. if (cFileName.Equals(".", StringComparison.OrdinalIgnoreCase))
  133. {
  134. return false;
  135. }
  136. if (cFileName.Equals("..", StringComparison.OrdinalIgnoreCase))
  137. {
  138. return false;
  139. }
  140. if (!includeFiles && !attributes.HasFlag(FileAttributes.Directory))
  141. {
  142. return false;
  143. }
  144. if (!includeDirectories && attributes.HasFlag(FileAttributes.Directory))
  145. {
  146. return false;
  147. }
  148. return true;
  149. }
  150. /// <summary>
  151. /// The space char
  152. /// </summary>
  153. private const char SpaceChar = ' ';
  154. /// <summary>
  155. /// The invalid file name chars
  156. /// </summary>
  157. private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();
  158. /// <summary>
  159. /// Takes a filename and removes invalid characters
  160. /// </summary>
  161. /// <param name="filename">The filename.</param>
  162. /// <returns>System.String.</returns>
  163. /// <exception cref="System.ArgumentNullException">filename</exception>
  164. public static string GetValidFilename(string filename)
  165. {
  166. if (string.IsNullOrEmpty(filename))
  167. {
  168. throw new ArgumentNullException("filename");
  169. }
  170. foreach (var c in InvalidFileNameChars)
  171. {
  172. filename = filename.Replace(c, SpaceChar);
  173. }
  174. return filename;
  175. }
  176. /// <summary>
  177. /// Resolves the shortcut.
  178. /// </summary>
  179. /// <param name="filename">The filename.</param>
  180. /// <returns>System.String.</returns>
  181. /// <exception cref="System.ArgumentNullException">filename</exception>
  182. public static string ResolveShortcut(string filename)
  183. {
  184. if (string.IsNullOrEmpty(filename))
  185. {
  186. throw new ArgumentNullException("filename");
  187. }
  188. var link = new ShellLink();
  189. ((IPersistFile)link).Load(filename, NativeMethods.STGM_READ);
  190. // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
  191. // ((IShellLinkW)link).Resolve(hwnd, 0)
  192. var sb = new StringBuilder(NativeMethods.MAX_PATH);
  193. WIN32_FIND_DATA data;
  194. ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
  195. return sb.ToString();
  196. }
  197. /// <summary>
  198. /// Creates a shortcut file pointing to a specified path
  199. /// </summary>
  200. /// <param name="shortcutPath">The shortcut path.</param>
  201. /// <param name="target">The target.</param>
  202. /// <exception cref="System.ArgumentNullException">shortcutPath</exception>
  203. public static void CreateShortcut(string shortcutPath, string target)
  204. {
  205. if (string.IsNullOrEmpty(shortcutPath))
  206. {
  207. throw new ArgumentNullException("shortcutPath");
  208. }
  209. if (string.IsNullOrEmpty(target))
  210. {
  211. throw new ArgumentNullException("target");
  212. }
  213. var link = new ShellLink();
  214. ((IShellLinkW)link).SetPath(target);
  215. ((IPersistFile)link).Save(shortcutPath, true);
  216. }
  217. /// <summary>
  218. /// Determines whether the specified filename is shortcut.
  219. /// </summary>
  220. /// <param name="filename">The filename.</param>
  221. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  222. /// <exception cref="System.ArgumentNullException">filename</exception>
  223. public static bool IsShortcut(string filename)
  224. {
  225. if (string.IsNullOrEmpty(filename))
  226. {
  227. throw new ArgumentNullException("filename");
  228. }
  229. return string.Equals(Path.GetExtension(filename), ".lnk", StringComparison.OrdinalIgnoreCase);
  230. }
  231. /// <summary>
  232. /// Copies all.
  233. /// </summary>
  234. /// <param name="source">The source.</param>
  235. /// <param name="target">The target.</param>
  236. /// <exception cref="System.ArgumentNullException">source</exception>
  237. /// <exception cref="System.ArgumentException">The source and target directories are the same</exception>
  238. public static void CopyAll(string source, string target)
  239. {
  240. if (string.IsNullOrEmpty(source))
  241. {
  242. throw new ArgumentNullException("source");
  243. }
  244. if (string.IsNullOrEmpty(target))
  245. {
  246. throw new ArgumentNullException("target");
  247. }
  248. if (source.Equals(target, StringComparison.OrdinalIgnoreCase))
  249. {
  250. throw new ArgumentException("The source and target directories are the same");
  251. }
  252. // Check if the target directory exists, if not, create it.
  253. if (!Directory.Exists(target))
  254. {
  255. Directory.CreateDirectory(target);
  256. }
  257. foreach (var file in Directory.EnumerateFiles(source))
  258. {
  259. File.Copy(file, Path.Combine(target, Path.GetFileName(file)), true);
  260. }
  261. // Copy each subdirectory using recursion.
  262. foreach (var dir in Directory.EnumerateDirectories(source))
  263. {
  264. CopyAll(dir, Path.Combine(target, Path.GetFileName(dir)));
  265. }
  266. }
  267. /// <summary>
  268. /// Parses the ini file.
  269. /// </summary>
  270. /// <param name="path">The path.</param>
  271. /// <returns>NameValueCollection.</returns>
  272. public static NameValueCollection ParseIniFile(string path)
  273. {
  274. var values = new NameValueCollection();
  275. foreach (var line in File.ReadAllLines(path))
  276. {
  277. var data = line.Split('=');
  278. if (data.Length < 2) continue;
  279. var key = data[0];
  280. var value = data.Length == 2 ? data[1] : string.Join(string.Empty, data, 1, data.Length - 1);
  281. values[key] = value;
  282. }
  283. return values;
  284. }
  285. }
  286. }