FileSystem.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 file system entries within a foler
  70. /// </summary>
  71. /// <param name="path">The path.</param>
  72. /// <param name="searchPattern">The search pattern.</param>
  73. /// <param name="includeFiles">if set to <c>true</c> [include files].</param>
  74. /// <param name="includeDirectories">if set to <c>true</c> [include directories].</param>
  75. /// <returns>IEnumerable{WIN32_FIND_DATA}.</returns>
  76. /// <exception cref="System.ArgumentNullException">path</exception>
  77. /// <exception cref="System.IO.IOException">GetFileSystemEntries failed</exception>
  78. public static IEnumerable<WIN32_FIND_DATA> GetFileSystemEntries(string path, string searchPattern = "*", bool includeFiles = true, bool includeDirectories = true)
  79. {
  80. if (string.IsNullOrEmpty(path))
  81. {
  82. throw new ArgumentNullException("path");
  83. }
  84. var lpFileName = Path.Combine(path, searchPattern);
  85. WIN32_FIND_DATA lpFindFileData;
  86. var handle = NativeMethods.FindFirstFileEx(lpFileName, FINDEX_INFO_LEVELS.FindExInfoBasic, out lpFindFileData,
  87. FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FindFirstFileExFlags.FIND_FIRST_EX_LARGE_FETCH);
  88. if (handle == IntPtr.Zero)
  89. {
  90. var hr = Marshal.GetLastWin32Error();
  91. if (hr != 2 && hr != 0x12)
  92. {
  93. throw new IOException("GetFileSystemEntries failed");
  94. }
  95. yield break;
  96. }
  97. if (IncludeInFindFileOutput(lpFindFileData.cFileName, lpFindFileData.dwFileAttributes, includeFiles, includeDirectories))
  98. {
  99. lpFindFileData.Path = Path.Combine(path, lpFindFileData.cFileName);
  100. yield return lpFindFileData;
  101. }
  102. while (NativeMethods.FindNextFile(handle, out lpFindFileData) != IntPtr.Zero)
  103. {
  104. if (IncludeInFindFileOutput(lpFindFileData.cFileName, lpFindFileData.dwFileAttributes, includeFiles, includeDirectories))
  105. {
  106. lpFindFileData.Path = Path.Combine(path, lpFindFileData.cFileName);
  107. yield return lpFindFileData;
  108. }
  109. }
  110. NativeMethods.FindClose(handle);
  111. }
  112. /// <summary>
  113. /// Includes the in find file output.
  114. /// </summary>
  115. /// <param name="cFileName">Name of the c file.</param>
  116. /// <param name="attributes">The attributes.</param>
  117. /// <param name="includeFiles">if set to <c>true</c> [include files].</param>
  118. /// <param name="includeDirectories">if set to <c>true</c> [include directories].</param>
  119. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  120. public static bool IncludeInFindFileOutput(string cFileName, FileAttributes attributes, bool includeFiles, bool includeDirectories)
  121. {
  122. if (cFileName.Equals(".", StringComparison.OrdinalIgnoreCase))
  123. {
  124. return false;
  125. }
  126. if (cFileName.Equals("..", StringComparison.OrdinalIgnoreCase))
  127. {
  128. return false;
  129. }
  130. if (!includeFiles && !attributes.HasFlag(FileAttributes.Directory))
  131. {
  132. return false;
  133. }
  134. if (!includeDirectories && attributes.HasFlag(FileAttributes.Directory))
  135. {
  136. return false;
  137. }
  138. return true;
  139. }
  140. /// <summary>
  141. /// The space char
  142. /// </summary>
  143. private const char SpaceChar = ' ';
  144. /// <summary>
  145. /// The invalid file name chars
  146. /// </summary>
  147. private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();
  148. /// <summary>
  149. /// Takes a filename and removes invalid characters
  150. /// </summary>
  151. /// <param name="filename">The filename.</param>
  152. /// <returns>System.String.</returns>
  153. /// <exception cref="System.ArgumentNullException">filename</exception>
  154. public static string GetValidFilename(string filename)
  155. {
  156. if (string.IsNullOrEmpty(filename))
  157. {
  158. throw new ArgumentNullException("filename");
  159. }
  160. foreach (var c in InvalidFileNameChars)
  161. {
  162. filename = filename.Replace(c, SpaceChar);
  163. }
  164. return filename;
  165. }
  166. /// <summary>
  167. /// Resolves the shortcut.
  168. /// </summary>
  169. /// <param name="filename">The filename.</param>
  170. /// <returns>System.String.</returns>
  171. /// <exception cref="System.ArgumentNullException">filename</exception>
  172. public static string ResolveShortcut(string filename)
  173. {
  174. if (string.IsNullOrEmpty(filename))
  175. {
  176. throw new ArgumentNullException("filename");
  177. }
  178. var link = new ShellLink();
  179. ((IPersistFile)link).Load(filename, NativeMethods.STGM_READ);
  180. // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
  181. // ((IShellLinkW)link).Resolve(hwnd, 0)
  182. var sb = new StringBuilder(NativeMethods.MAX_PATH);
  183. WIN32_FIND_DATA data;
  184. ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
  185. return sb.ToString();
  186. }
  187. /// <summary>
  188. /// Creates a shortcut file pointing to a specified path
  189. /// </summary>
  190. /// <param name="shortcutPath">The shortcut path.</param>
  191. /// <param name="target">The target.</param>
  192. /// <exception cref="System.ArgumentNullException">shortcutPath</exception>
  193. public static void CreateShortcut(string shortcutPath, string target)
  194. {
  195. if (string.IsNullOrEmpty(shortcutPath))
  196. {
  197. throw new ArgumentNullException("shortcutPath");
  198. }
  199. if (string.IsNullOrEmpty(target))
  200. {
  201. throw new ArgumentNullException("target");
  202. }
  203. var link = new ShellLink();
  204. ((IShellLinkW)link).SetPath(target);
  205. ((IPersistFile)link).Save(shortcutPath, true);
  206. }
  207. /// <summary>
  208. /// Determines whether the specified filename is shortcut.
  209. /// </summary>
  210. /// <param name="filename">The filename.</param>
  211. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  212. /// <exception cref="System.ArgumentNullException">filename</exception>
  213. public static bool IsShortcut(string filename)
  214. {
  215. if (string.IsNullOrEmpty(filename))
  216. {
  217. throw new ArgumentNullException("filename");
  218. }
  219. return string.Equals(Path.GetExtension(filename), ".lnk", StringComparison.OrdinalIgnoreCase);
  220. }
  221. /// <summary>
  222. /// Copies all.
  223. /// </summary>
  224. /// <param name="source">The source.</param>
  225. /// <param name="target">The target.</param>
  226. /// <exception cref="System.ArgumentNullException">source</exception>
  227. /// <exception cref="System.ArgumentException">The source and target directories are the same</exception>
  228. public static void CopyAll(string source, string target)
  229. {
  230. if (string.IsNullOrEmpty(source))
  231. {
  232. throw new ArgumentNullException("source");
  233. }
  234. if (string.IsNullOrEmpty(target))
  235. {
  236. throw new ArgumentNullException("target");
  237. }
  238. if (source.Equals(target, StringComparison.OrdinalIgnoreCase))
  239. {
  240. throw new ArgumentException("The source and target directories are the same");
  241. }
  242. // Check if the target directory exists, if not, create it.
  243. if (!Directory.Exists(target))
  244. {
  245. Directory.CreateDirectory(target);
  246. }
  247. foreach (var file in Directory.EnumerateFiles(source))
  248. {
  249. File.Copy(file, Path.Combine(target, Path.GetFileName(file)), true);
  250. }
  251. // Copy each subdirectory using recursion.
  252. foreach (var dir in Directory.EnumerateDirectories(source))
  253. {
  254. CopyAll(dir, Path.Combine(target, Path.GetFileName(dir)));
  255. }
  256. }
  257. /// <summary>
  258. /// Parses the ini file.
  259. /// </summary>
  260. /// <param name="path">The path.</param>
  261. /// <returns>NameValueCollection.</returns>
  262. public static NameValueCollection ParseIniFile(string path)
  263. {
  264. var values = new NameValueCollection();
  265. foreach (var line in File.ReadAllLines(path))
  266. {
  267. var data = line.Split('=');
  268. if (data.Length < 2) continue;
  269. var key = data[0];
  270. var value = data.Length == 2 ? data[1] : string.Join(string.Empty, data, 1, data.Length - 1);
  271. values[key] = value;
  272. }
  273. return values;
  274. }
  275. }
  276. }