FileSystem.cs 12 KB

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