2
0

FileSystem.cs 13 KB

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