You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

709 lines
26 KiB

  1. using Apewer.Internals;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Reflection;
  6. using System.Security.Permissions;
  7. namespace Apewer
  8. {
  9. /// <summary>存储实用工具。</summary>
  10. public static class StorageUtility
  11. {
  12. private static Exception Try(Action action)
  13. {
  14. try { action?.Invoke(); return null; }
  15. catch (Exception ex) { return ex; }
  16. }
  17. /// <summary>文件操作线程锁。</summary>
  18. public static object Locker = new object();
  19. #region delete
  20. /// <summary>删除文件。</summary>
  21. public static Exception DeleteFile(string path, bool useTemp = false)
  22. {
  23. if (useTemp)
  24. {
  25. try
  26. {
  27. if (string.IsNullOrEmpty(path)) return new ArgumentException();
  28. if (!File.Exists(path)) return new FileNotFoundException();
  29. Try(() => new FileInfo(path).Attributes = FileAttributes.Normal);
  30. var temp = Environment.GetEnvironmentVariable("TEMP");
  31. var name = Path.GetFileName(path);
  32. var dest = null as string;
  33. while (dest == null || File.Exists(dest))
  34. {
  35. var guid = Guid.NewGuid().ToString("n").Substring(0, 8);
  36. dest = $"trash_{guid}_{name}";
  37. }
  38. File.Move(path, dest);
  39. File.Delete(dest);
  40. return null;
  41. }
  42. catch (Exception ex) { return ex; }
  43. }
  44. try
  45. {
  46. File.Delete(path);
  47. return null;
  48. }
  49. catch (Exception ex) { return ex; }
  50. }
  51. /// <summary>删除目录、子目录和子文件。</summary>
  52. public static Exception DeleteDirectory(string path, bool useTemp = false)
  53. {
  54. if (useTemp)
  55. {
  56. try
  57. {
  58. if (string.IsNullOrEmpty(path)) return new ArgumentException();
  59. if (!Directory.Exists(path)) return new DirectoryNotFoundException();
  60. var temp = Environment.GetEnvironmentVariable("TEMP");
  61. var name = Path.GetDirectoryName(path);
  62. var dest = null as string;
  63. while (dest == null || Directory.Exists(dest))
  64. {
  65. var guid = Guid.NewGuid().ToString("n").Substring(0, 8);
  66. dest = $"trash_{guid}_{name}";
  67. }
  68. Directory.Move(path, dest);
  69. Directory.Delete(dest, true);
  70. return null;
  71. }
  72. catch (Exception ex) { return ex; }
  73. }
  74. try
  75. {
  76. Directory.Delete(path, true);
  77. return null;
  78. }
  79. catch (Exception ex) { return ex; }
  80. }
  81. #endregion
  82. #region path
  83. /// <summary>无效的路径字符。</summary>
  84. public static char[] InvalidPathChars
  85. {
  86. get => new char[] {
  87. '\\', '/', '\'', '"', ':', '*', '?', '<', '>', '|',
  88. '\0', '\a', '\b', '\t', '\n', '\v', '\f', '\r',
  89. '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u000e', '\u000f',
  90. '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
  91. '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f'
  92. };
  93. }
  94. /// <summary>合并路径。</summary>
  95. public static string CombinePath(params string[] paths)
  96. {
  97. if (paths == null || paths.Length < 1) return "";
  98. try
  99. {
  100. #if NET20
  101. var result = paths[0];
  102. for (var i = 0; i < paths.Length; i++)
  103. {
  104. result = Path.Combine(result, paths[i]);
  105. }
  106. return result;
  107. #else
  108. return Path.Combine(paths);
  109. #endif
  110. }
  111. catch { return ""; }
  112. }
  113. /// <summary>获取文件或目录的存在状态。</summary>
  114. public static bool PathExists(string path)
  115. {
  116. if (string.IsNullOrEmpty(path)) return false;
  117. if (File.Exists(path)) return true;
  118. if (Directory.Exists(path)) return true;
  119. return false;
  120. }
  121. /// <summary>获取目录的存在状态。</summary>
  122. public static bool DirectoryExists(string path) => string.IsNullOrEmpty(path) ? false : Directory.Exists(path);
  123. /// <summary>获取文件的存在状态。</summary>
  124. public static bool FileExists(string path) => string.IsNullOrEmpty(path) ? false : File.Exists(path);
  125. /// <summary>获取文件或目录的上级目录完整路径,失败时返回 NULL 值。。</summary>
  126. public static string GetParentPath(string path)
  127. {
  128. try
  129. {
  130. if (File.Exists(path)) return Path.GetDirectoryName(path);
  131. if (Directory.Exists(path)) return Directory.GetParent(path).FullName;
  132. }
  133. catch { }
  134. return null;
  135. }
  136. /// <summary>修正文件名,去除不允许的字符。</summary>
  137. public static string FixFileName(string fileName)
  138. {
  139. var result = fileName;
  140. if (string.IsNullOrEmpty(result))
  141. {
  142. result = Constant.EmptyString;
  143. }
  144. else
  145. {
  146. var invalid = InvalidPathChars;
  147. foreach (var c in invalid) result = result.Replace(c.ToString(), "");
  148. }
  149. if (result.Length > 0) result = result.Trim();
  150. return result;
  151. }
  152. /// <summary>获取指定目录的子目录,可指定递归子目录。</summary>
  153. public static List<string> GetSubDirectories(string directory, bool recursive = false, bool recurPrecedence = true) => GetSubDirectories(directory, recursive ? -1 : 0, recurPrecedence);
  154. /// <summary>获取指定目录下子目录的路径。</summary>
  155. /// <param name="directory">顶级目录。</param>
  156. /// <param name="recurDepth">子目录递归深度,指定为 0 时不递归,指定为 -1 时无限递归。</param>
  157. /// <param name="recurPrecedence">优先排列递归项。</param>
  158. public static List<string> GetSubDirectories(string directory, int recurDepth, bool recurPrecedence = true)
  159. {
  160. var list = new List<string>();
  161. if (string.IsNullOrEmpty(directory)) return list;
  162. var directories = new string[0];
  163. try
  164. {
  165. directories = Directory.GetDirectories(directory);
  166. }
  167. catch { }
  168. foreach (var d in directories)
  169. {
  170. var recurlist = new List<string>();
  171. if (recurDepth != 0)
  172. {
  173. var depth = (recurDepth > 0) ? recurDepth - 1 : recurDepth;
  174. var subrecur = GetSubDirectories(d, depth, recurPrecedence);
  175. recurlist.AddRange(subrecur);
  176. }
  177. if (recurPrecedence)
  178. {
  179. list.AddRange(recurlist);
  180. list.Add(d);
  181. }
  182. else
  183. {
  184. list.Add(d);
  185. list.AddRange(recurlist);
  186. }
  187. }
  188. return list;
  189. }
  190. /// <summary>获取指定目录的子文件,可指定递归子目录。</summary>
  191. public static List<string> GetSubFiles(string path, bool recursive = false, bool recurPrecedence = true) => GetSubFiles(path, recursive ? -1 : 0, recurPrecedence);
  192. /// <summary>获取指定目录下子文件的路径。</summary>
  193. /// <param name="directory">顶级目录。</param>
  194. /// <param name="recurDepth">子目录递归深度,指定为 0 时不递归,指定为 -1 时无限递归。</param>
  195. /// <param name="recurPrecedence">优先排列递归项。</param>
  196. public static List<string> GetSubFiles(string directory, int recurDepth, bool recurPrecedence = true)
  197. {
  198. var list = new List<string>();
  199. if (string.IsNullOrEmpty(directory)) return list;
  200. var dirs = new List<string>();
  201. if (recurDepth == 0)
  202. {
  203. dirs.Add(directory);
  204. }
  205. else
  206. {
  207. var recurdicrotylist = GetSubDirectories(directory, recurDepth, recurPrecedence);
  208. if (recurPrecedence)
  209. {
  210. dirs.AddRange(recurdicrotylist);
  211. dirs.Add(directory);
  212. }
  213. else
  214. {
  215. dirs.Add(directory);
  216. dirs.AddRange(recurdicrotylist);
  217. }
  218. }
  219. foreach (var d in dirs)
  220. {
  221. try
  222. {
  223. var files = System.IO.Directory.GetFiles(d);
  224. list.AddRange(files);
  225. }
  226. catch { }
  227. }
  228. return list;
  229. }
  230. #endregion
  231. #region directory
  232. /// <summary>确信指定存在指定目录。</summary>
  233. public static bool AssureDirectory(string path)
  234. {
  235. if (string.IsNullOrEmpty(path)) return false;
  236. try
  237. {
  238. if (File.Exists(path)) return false;
  239. if (Directory.Exists(path)) return true;
  240. var created = Directory.CreateDirectory(path);
  241. return created.Exists;
  242. }
  243. catch { }
  244. return false;
  245. }
  246. /// <summary>确信指定存在指定路径所在的上级目录。</summary>
  247. public static bool AssureParent(string path)
  248. {
  249. if (string.IsNullOrEmpty(path)) return false;
  250. var parent = Constant.EmptyString;
  251. try { parent = Directory.GetParent(path).FullName; } catch { }
  252. var result = AssureDirectory(parent);
  253. return result;
  254. }
  255. #endregion
  256. #region file
  257. /// <summary>打开文件,并获取文件流。若文件不存在,则先创建文件;若获取失败,则返回 NULL 值。可选文件的锁定状态。</summary>
  258. public static FileStream OpenFile(string path, bool share = true)
  259. {
  260. try
  261. {
  262. if (string.IsNullOrEmpty(path)) return null;
  263. if (DirectoryExists(path)) return null;
  264. if (AssureParent(path))
  265. {
  266. var m = FileMode.OpenOrCreate;
  267. var a = FileAccess.ReadWrite;
  268. var s = share ? FileShare.ReadWrite : FileShare.None;
  269. var stream = new FileStream(path, m, a, s);
  270. return stream;
  271. }
  272. }
  273. catch { }
  274. return null;
  275. }
  276. /// <summary>创建一个空文件且不保留句柄。</summary>
  277. /// <param name="path">文件路径,若已存在则返回失败。</param>
  278. /// <param name="length">文件长度(字节数)。</param>
  279. /// <param name="replace">替换现有文件。</param>
  280. /// <returns>创建成功。</returns>
  281. public static bool CreateFile(string path, long length = 0, bool replace = false)
  282. {
  283. if (string.IsNullOrEmpty(path)) return false;
  284. if (!replace && File.Exists(path)) return false;
  285. lock (Locker)
  286. {
  287. var file = null as FileStream;
  288. var success = false;
  289. try
  290. {
  291. var m = replace ? FileMode.Create : FileMode.OpenOrCreate;
  292. file = new FileStream(path, m, FileAccess.ReadWrite, FileShare.ReadWrite);
  293. if (length > 0) file.SetLength(length);
  294. success = true;
  295. }
  296. catch { }
  297. RuntimeUtility.Dispose(file);
  298. return success;
  299. }
  300. }
  301. /// <summary>复制文件。</summary>
  302. /// <param name="source">旧路径。</param>
  303. /// <param name="destination">新路径。</param>
  304. /// <param name="replace">新路径存在时,替换新文件。</param>
  305. public static bool CopyFile(string source, string destination, bool replace = true)
  306. {
  307. if (string.IsNullOrEmpty(source)) return false;
  308. if (string.IsNullOrEmpty(destination)) return false;
  309. lock (Locker)
  310. {
  311. if (!FileExists(source)) return false;
  312. try
  313. {
  314. File.Copy(source, destination, replace);
  315. return true;
  316. }
  317. catch { return false; }
  318. }
  319. }
  320. /// <summary>向文件追加数据。文件不存在时将创建。</summary>
  321. public static bool AppendFile(string path, params byte[] bytes)
  322. {
  323. if (bytes == null || bytes.Length < 1) return false;
  324. lock (Locker)
  325. {
  326. var assured = AssureParent(path);
  327. if (!assured) return false;
  328. using (var file = OpenFile(path, true))
  329. {
  330. if (file == null) return false;
  331. try
  332. {
  333. file.Position = file.Length;
  334. file.Write(bytes, 0, bytes.Length);
  335. file.Flush();
  336. return true;
  337. }
  338. catch { return false; }
  339. }
  340. }
  341. }
  342. /// <summary>将数据写入新文件,若文件已存在则覆盖。</summary>
  343. public static bool WriteFile(string path, params byte[] bytes) => WriteFile(path, false, bytes);
  344. /// <summary>将数据写入新文件,若文件已存在则覆盖。</summary>
  345. public static bool WriteFile(string path, bool bom, params byte[] bytes)
  346. {
  347. if (string.IsNullOrEmpty(path)) return false;
  348. if (bom)
  349. {
  350. lock (Locker)
  351. {
  352. if (bytes == null || bytes.Length < 1)
  353. {
  354. try
  355. {
  356. File.WriteAllBytes(path, TextUtility.Bom);
  357. return true;
  358. }
  359. catch
  360. {
  361. return false;
  362. }
  363. }
  364. else
  365. {
  366. var file = OpenFile(path, true);
  367. var success = false;
  368. try
  369. {
  370. var write1 = BinaryUtility.Write(file, TextUtility.Bom);
  371. if (write1 == TextUtility.Bom.Length)
  372. {
  373. var write2 = BinaryUtility.Write(file, bytes);
  374. if (bytes != null && bytes.LongLength > 0L)
  375. {
  376. }
  377. success = true;
  378. }
  379. }
  380. catch { }
  381. RuntimeUtility.Dispose(file);
  382. return success;
  383. }
  384. }
  385. }
  386. else
  387. {
  388. lock (Locker)
  389. {
  390. try
  391. {
  392. File.WriteAllBytes(path, bytes);
  393. return true;
  394. }
  395. catch
  396. {
  397. return false;
  398. }
  399. }
  400. }
  401. }
  402. /// <summary>将数据写入新文件,若文件已存在则覆盖。</summary>
  403. public static bool WriteFile(string path, Json json, bool bom = false)
  404. {
  405. if (string.IsNullOrEmpty(path)) return false;
  406. if (json == null || json.IsNull || json.IsNone) return false;
  407. var text = json.ToString(true);
  408. var bytes = TextUtility.ToBinary(text);
  409. return WriteFile(path, bom, bytes);
  410. }
  411. /// <summary>读取文件,获取文件内容。当文件为 UTF-8 文本文件时,可去除 BOM 头。</summary>
  412. public static byte[] ReadFile(string path, bool wipeBom = false)
  413. {
  414. if (!FileExists(path)) return Constant.EmptyBytes;
  415. lock (Locker)
  416. {
  417. try
  418. {
  419. var bytes = File.ReadAllBytes(path);
  420. if (wipeBom) bytes = BinaryUtility.WipeTextBom(bytes);
  421. return bytes;
  422. }
  423. catch { }
  424. }
  425. return Constant.EmptyBytes;
  426. }
  427. /// <summary>获取指定文件的字节数,获取失败时返回 -1 值。</summary>
  428. public static long GetFileLength(string path)
  429. {
  430. try
  431. {
  432. var info = new FileInfo(path);
  433. return info.Length;
  434. }
  435. catch { }
  436. return -1;
  437. }
  438. #endregion
  439. /// <summary>获取文件的最后写入时间。</summary>
  440. public static DateTime GetFileLastWriteTime(string path, bool utc = false)
  441. {
  442. try
  443. {
  444. var info = new FileInfo(path);
  445. return utc ? info.LastWriteTimeUtc : info.LastWriteTime;
  446. }
  447. catch { }
  448. return new DateTime();
  449. }
  450. /// <summary>设置文件的最后写入时间。</summary>
  451. public static string SetFileLastWriteTime(string path, DateTime value)
  452. {
  453. try
  454. {
  455. var info = new FileInfo(path);
  456. info.LastWriteTime = value;
  457. return null;
  458. }
  459. catch (Exception ex)
  460. {
  461. return ex.Message;
  462. }
  463. }
  464. /// <summary>压缩文件到流。</summary>
  465. /// <param name="files">Key 为 ZIP 内的文件名,Value 为原始文件路径。</param>
  466. /// <param name="output">要输出的 ZIP 流。</param>
  467. public static Exception ToZip(Dictionary<string, string> files, Stream output)
  468. {
  469. if (files == null) return new ArgumentNullException(nameof(files));
  470. var streams = new List<Stream>();
  471. var ex = BinaryUtility.ToZip(files.Keys, output, (name) =>
  472. {
  473. if (name.IsEmpty()) return null;
  474. var path = files[name];
  475. if (path.IsEmpty()) return null;
  476. if (!FileExists(path)) return null;
  477. var input = OpenFile(path);
  478. streams.Add(input);
  479. return input;
  480. }, (name) => GetFileLastWriteTime(files[name]), true);
  481. RuntimeUtility.Dispose(streams);
  482. return ex;
  483. }
  484. /// <summary>压缩文件到流。</summary>
  485. /// <param name="files">Key 为 ZIP 内的文件名,Value 为原始文件路径。</param>
  486. /// <param name="output">要输出的 ZIP 文件路径,已存在的文件将被删除。</param>
  487. public static Exception ToZip(Dictionary<string, string> files, string output)
  488. {
  489. if (output.IsEmpty()) return new ArgumentException(nameof(output));
  490. if (FileExists(output)) DeleteFile(output);
  491. if (FileExists(output)) return new IOException();
  492. var stream = OpenFile(output);
  493. if (stream == null) return new IOException();
  494. var ex = ToZip(files, stream);
  495. RuntimeUtility.Dispose(stream, true);
  496. return ex;
  497. }
  498. /// <summary>压缩文件到流。</summary>
  499. /// <param name="directory">原始文件目录。</param>
  500. /// <param name="output">要输出的 ZIP 流。</param>
  501. public static Exception ToZip(string directory, Stream output)
  502. {
  503. if (!DirectoryExists(directory)) return new DirectoryNotFoundException();
  504. var dict = new Dictionary<string, string>();
  505. foreach (var path in GetSubFiles(directory, true))
  506. {
  507. var name = path.Substring(directory.Length);
  508. if (name.StartsWith("\\")) name = name.Substring(1);
  509. if (name.StartsWith("/")) name = name.Substring(1);
  510. dict.Add(name, path);
  511. }
  512. return ToZip(dict, output);
  513. }
  514. /// <summary>压缩文件到流。</summary>
  515. /// <param name="directory">原始文件目录。</param>
  516. /// <param name="output">要输出的 ZIP 文件路径,已存在的旧文件将被删除。</param>
  517. public static Exception ToZip(string directory, string output)
  518. {
  519. if (output.IsEmpty()) return new ArgumentException(nameof(output));
  520. if (FileExists(output)) DeleteFile(output);
  521. if (FileExists(output)) return new IOException("无法删除现有文件。");
  522. var stream = OpenFile(output);
  523. if (stream == null) return new IOException("无法创建文件。");
  524. var ex = ToZip(directory, stream);
  525. RuntimeUtility.Dispose(stream, true);
  526. return ex;
  527. }
  528. /// <summary>解压 ZIP 文件到目标目录。已存在的旧文件将被删除。</summary>
  529. public static Exception FromZip(string zipPath, string outputDirectory = null)
  530. {
  531. if (!FileExists(zipPath)) return new FileNotFoundException("指定的 ZIP 文件路径无效。");
  532. var directory = outputDirectory;
  533. if (directory.IsEmpty())
  534. {
  535. if (zipPath.SafeLower().EndsWith(".zip"))
  536. {
  537. directory = zipPath.Substring(0, zipPath.Length - 4);
  538. //if (directory.EndsWith("/") || directory.EndsWith("\\"))
  539. //if (PathExists(directory)) directory = null;
  540. }
  541. else
  542. {
  543. directory = GetParentPath(zipPath);
  544. }
  545. }
  546. if (directory.IsEmpty()) return new ArgumentException("无法判断目录路径。");
  547. if (!AssureDirectory(directory)) return new DirectoryNotFoundException("无法创建目录。");
  548. var input = OpenFile(zipPath);
  549. if (input == null) return new IOException("无法打开 ZIP 文件。");
  550. var info = new Dictionary<string, DateTime>();
  551. var ex = BinaryUtility.FromZip(input, (name, size, modifield) =>
  552. {
  553. var path = Path.Combine(directory, name);
  554. if (FileExists(path)) DeleteFile(path);
  555. if (DirectoryExists(path)) DeleteDirectory(path, true);
  556. if (PathExists(path)) throw new IOException("无法删除旧文件或旧目录。");
  557. var output = OpenFile(path);
  558. if (output == null) throw new IOException("无法创建文件 " + path + "。");
  559. if (info.ContainsKey(path))
  560. {
  561. RuntimeUtility.Dispose(output);
  562. return null;
  563. }
  564. info.Add(path, modifield);
  565. return output;
  566. }, (name, modified) =>
  567. {
  568. var path = Path.Combine(directory, name);
  569. var exists = AssureDirectory(path);
  570. if (!exists) throw new IOException("无法创建 ZIP 中对应的目录。");
  571. }, true);
  572. // 恢复文件的修改时间。
  573. foreach (var i in info) SetFileLastWriteTime(i.Key, i.Value);
  574. return ex;
  575. }
  576. ///// <summary>解压 ZIP 文件到字典。失败且不允许异常时返回 NULL 值。</summary>
  577. //public static Dictionary<string, byte[]> FromZip(string zipPath, bool allowException = false)
  578. //{
  579. // if (FileExists(zipPath))
  580. // {
  581. // var ex = new FileNotFoundException("文件不存在。");
  582. // if (allowException) throw ex;
  583. // return null;
  584. // }
  585. // var input = OpenFile(zipPath);
  586. // if (input == null)
  587. // {
  588. // var ex = new IOException("无法打开 ZIP 文件。");
  589. // if (allowException) throw ex;
  590. // return null;
  591. // }
  592. // return BinaryUtility.FromZip(input, ;
  593. //}
  594. /// <summary>获取指定程序集的资源。</summary>
  595. public static Stream GetResource(string name, Assembly assembly = null)
  596. {
  597. try
  598. {
  599. if (assembly == null) assembly = Assembly.GetExecutingAssembly();
  600. var stream = assembly.GetManifestResourceStream(name);
  601. return stream;
  602. }
  603. catch { }
  604. return null;
  605. }
  606. /// <summary>获取当前进程程序集的资源。读取失败时返回 NULL 值。</summary>
  607. public static byte[] ReadResource(string name, Assembly assembly = null)
  608. {
  609. var stream = GetResource(name, assembly);
  610. if (stream == null) return null;
  611. var bytes = BinaryUtility.Read(stream, true);
  612. return bytes;
  613. }
  614. /// <summary>监视文件夹的变化。</summary>
  615. public static FileSystemWatcher NewFileSystemWatcher(string directory, FileSystemEventHandler action)
  616. {
  617. var watcher = new FileSystemWatcher();
  618. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite | NotifyFilters.Size;
  619. watcher.IncludeSubdirectories = true;
  620. watcher.Path = directory;
  621. watcher.Created += (s, e) => action?.Invoke(watcher, e);
  622. watcher.Deleted += (s, e) => action?.Invoke(watcher, e);
  623. watcher.Changed += (s, e) => action?.Invoke(watcher, e);
  624. watcher.Renamed += (s, e) => action?.Invoke(watcher, e);
  625. watcher.EnableRaisingEvents = true;
  626. return watcher;
  627. }
  628. }
  629. }