FileHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. using SWRIS.Extensions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. namespace SWRIS.Core
  11. {
  12. public class FileHelper
  13. {
  14. public static string FileToString(string filePath)
  15. {
  16. return FileToString(filePath, Encoding.UTF8);
  17. }
  18. public static string FileToString(string filePath, Encoding encoding)
  19. {
  20. string result;
  21. if (!File.Exists(filePath))
  22. {
  23. result = string.Empty;
  24. }
  25. else
  26. {
  27. try
  28. {
  29. using (StreamReader streamReader = new StreamReader(filePath, encoding))
  30. {
  31. result = streamReader.ReadToEnd();
  32. }
  33. }
  34. catch (Exception ex)
  35. {
  36. throw ex;
  37. }
  38. }
  39. return result;
  40. }
  41. public static FileStream FileToStream(string path)
  42. {
  43. ArgumentNotNullOrEmpty(path, "path");
  44. return new FileStream(path, FileMode.Open, FileAccess.Read);
  45. }
  46. public static byte[] FileToBytes(string filePath, int len = 0, int start = 0)
  47. {
  48. byte[] result;
  49. using (FileStream fileStream = FileToStream(filePath))
  50. {
  51. int num = (fileStream.Length > 2147483647L) ? int.MaxValue : ((int)fileStream.Length);
  52. int num2 = (len == 0) ? num : len;
  53. num2 = ((num2 >= num) ? num : num2);
  54. byte[] array = new byte[num2];
  55. fileStream.Read(array, start, num2);
  56. result = array;
  57. }
  58. return result;
  59. }
  60. public static void CreateDirectory(string directoryPath)
  61. {
  62. if (!string.IsNullOrEmpty(directoryPath))
  63. {
  64. if (!Directory.Exists(directoryPath))
  65. {
  66. ThreadPool.QueueUserWorkItem(delegate (object obj)
  67. {
  68. try
  69. {
  70. Directory.CreateDirectory(directoryPath);
  71. }
  72. catch (Exception ex)
  73. {
  74. LogHelper.Error(string.Format("文件夹{0}创建失败", directoryPath), ex);
  75. }
  76. });
  77. }
  78. }
  79. }
  80. public static string CreateFileDirectory(string filePath)
  81. {
  82. string filePath2 = GetFilePath(filePath, '\\');
  83. CreateDirectory(filePath2);
  84. return filePath2;
  85. }
  86. public static void CreateFile(string filePath)
  87. {
  88. if (!string.IsNullOrEmpty(filePath))
  89. {
  90. try
  91. {
  92. if (!File.Exists(filePath))
  93. {
  94. string filePath2 = GetFilePath(filePath, '\\');
  95. CreateDirectory(filePath2);
  96. lock (_sync)
  97. {
  98. using (new FileStream(filePath, FileMode.OpenOrCreate))
  99. {
  100. }
  101. }
  102. }
  103. }
  104. catch (Exception innerException)
  105. {
  106. throw new Exception("创建文件异常", innerException);
  107. }
  108. }
  109. }
  110. public static string CreateFile(string filePath, byte[] buffer)
  111. {
  112. if (!string.IsNullOrEmpty(filePath))
  113. {
  114. filePath = GetFileSavaPath(filePath);
  115. try
  116. {
  117. FileInfo fileInfo = new FileInfo(filePath);
  118. using (FileStream fileStream = fileInfo.Create())
  119. {
  120. fileStream.Write(buffer, 0, buffer.Length);
  121. }
  122. return filePath;
  123. }
  124. catch
  125. {
  126. }
  127. }
  128. return null;
  129. }
  130. public static void CreateFile(string filePath, string text)
  131. {
  132. CreateFile(filePath, text, Encoding.GetEncoding("utf-8"));
  133. }
  134. public static void CreateFile(string filePath, string text, Encoding encoding)
  135. {
  136. if (filePath != null && !(filePath == string.Empty))
  137. {
  138. string filePath2 = GetFilePath(filePath, '\\');
  139. if (!Directory.Exists(filePath2))
  140. {
  141. Directory.CreateDirectory(filePath2);
  142. }
  143. FileInfo fileInfo = new FileInfo(filePath);
  144. using (FileStream fileStream = fileInfo.Create())
  145. {
  146. using (StreamWriter streamWriter = new StreamWriter(fileStream, encoding))
  147. {
  148. streamWriter.Write(text);
  149. streamWriter.Flush();
  150. }
  151. }
  152. }
  153. }
  154. public static void Open(params string[] path)
  155. {
  156. if (!path.IsInvalid<string>())
  157. {
  158. string text = FileHelper.ConnectPath(path);
  159. try
  160. {
  161. Process.Start("explorer.exe", text);
  162. }
  163. catch (Exception innerException)
  164. {
  165. throw new Exception("打开文件出现异常:" + text, innerException);
  166. }
  167. }
  168. }
  169. public static void DeleteFile(string filePath)
  170. {
  171. if (!filePath.IsInvalid())
  172. {
  173. try
  174. {
  175. if (File.Exists(filePath))
  176. {
  177. File.Delete(filePath);
  178. }
  179. }
  180. catch (Exception innerException)
  181. {
  182. throw new Exception("删除文件异常:" + filePath, innerException);
  183. }
  184. }
  185. }
  186. public static string GetFileName(string source, char separate = '\\')
  187. {
  188. string result;
  189. if (source.IsInvalid())
  190. {
  191. result = string.Empty;
  192. }
  193. else
  194. {
  195. source = source.TrimEnd(new char[]
  196. {
  197. separate
  198. });
  199. int num = source.LastIndexOf(separate);
  200. if (num > 0)
  201. {
  202. result = source.Substring(num + 1, source.Length - num - 1);
  203. }
  204. else
  205. {
  206. result = source;
  207. }
  208. }
  209. return result;
  210. }
  211. public static string GetFilePath(string source, char separate = '\\')
  212. {
  213. string result;
  214. if (source.IsInvalid())
  215. {
  216. result = string.Empty;
  217. }
  218. else
  219. {
  220. source = source.TrimEnd(new char[]
  221. {
  222. separate
  223. });
  224. int num = source.LastIndexOf(separate);
  225. if (num > 0)
  226. {
  227. result = source.Substring(0, num + 1);
  228. }
  229. else
  230. {
  231. result = source;
  232. }
  233. }
  234. return result;
  235. }
  236. public static string ConnectPath(char separate, params string[] path)
  237. {
  238. string result;
  239. if (path.IsInvalid<string>())
  240. {
  241. result = string.Empty;
  242. }
  243. else if (path.Length == 2)
  244. {
  245. result = string.Format("{0}{1}{2}", path[0].TrimEnd(new char[]
  246. {
  247. separate
  248. }), separate, path[1].TrimStart(new char[]
  249. {
  250. separate
  251. }));
  252. }
  253. else if (path.Length == 1)
  254. {
  255. result = path[0];
  256. }
  257. else
  258. {
  259. StringBuilder stringBuilder = new StringBuilder(32);
  260. foreach (string text in path)
  261. {
  262. stringBuilder.Append(text.TrimEnd(new char[]
  263. {
  264. separate
  265. }).TrimStart(new char[]
  266. {
  267. separate
  268. })).Append(separate);
  269. }
  270. result = stringBuilder.ToString().TrimEnd(new char[]
  271. {
  272. separate
  273. });
  274. }
  275. return result;
  276. }
  277. public static string ConnectPath(params string[] path)
  278. {
  279. return ConnectPath('\\', path);
  280. }
  281. public static string ConvertLinuxPath(string linuxpath, char validChar = '_')
  282. {
  283. int num = linuxpath.IndexOfAny(InvalidPathChars);
  284. string result;
  285. if (num >= 0)
  286. {
  287. result = ConvertLinuxPath(linuxpath.Replace(linuxpath[num], validChar), '_');
  288. }
  289. else
  290. {
  291. result = linuxpath.Replace('/', '\\');
  292. }
  293. return result;
  294. }
  295. public static string ConnectLinuxPath(string path1, string path2)
  296. {
  297. return ConnectPath('/', new string[]
  298. {
  299. path1,
  300. path2
  301. });
  302. }
  303. public static string GetLinuxFileName(string source)
  304. {
  305. return GetFileName(source, '/');
  306. }
  307. public static string GetLinuxFilePath(string source)
  308. {
  309. return GetFilePath(source, '/');
  310. }
  311. public static string GetExtension(string filePath)
  312. {
  313. ArgumentNotNullOrEmpty(filePath, "filePath");
  314. string result = string.Empty;
  315. try
  316. {
  317. result = Path.GetExtension(filePath).Replace(".", string.Empty);
  318. }
  319. catch (Exception)
  320. {
  321. }
  322. return result;
  323. }
  324. public static string TryGetExtension(string filename, char splitChar)
  325. {
  326. ArgumentNotNullOrEmpty(filename, "filePath");
  327. string[] source = filename.Split(new char[]
  328. {
  329. splitChar
  330. });
  331. string result = string.Empty;
  332. if (source.Any())
  333. {
  334. result = source.Last();
  335. }
  336. return result;
  337. }
  338. public static string GetPhysicalPath(string relativePath)
  339. {
  340. string result;
  341. if (string.IsNullOrEmpty(relativePath))
  342. {
  343. result = string.Empty;
  344. }
  345. else
  346. {
  347. relativePath = relativePath.Replace("/", "\\").Replace("~", string.Empty).Replace("~/", string.Empty);
  348. relativePath = (relativePath.StartsWith("\\") ? relativePath.Substring(1, relativePath.Length - 1) : relativePath);
  349. string applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
  350. string text = Path.Combine(applicationBase, relativePath);
  351. result = text;
  352. }
  353. return result;
  354. }
  355. public static string GetFileSize(string filePath)
  356. {
  357. ArgumentNotNullOrEmpty(filePath, "filePath");
  358. string result;
  359. if (!File.Exists(filePath))
  360. {
  361. result = string.Empty;
  362. }
  363. else
  364. {
  365. FileInfo fileInfo = new FileInfo(filePath);
  366. result = GetFileSize(fileInfo.Length, "F2");
  367. }
  368. return result;
  369. }
  370. public static long GetFileLength(string filepath)
  371. {
  372. long result = 0L;
  373. using (FileStream fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  374. {
  375. result = fileStream.Length;
  376. }
  377. return result;
  378. }
  379. public static string GetFileSize(long len, string format = "F2")
  380. {
  381. string result;
  382. if (len <= 0L)
  383. {
  384. result = "0 KB";
  385. }
  386. else
  387. {
  388. string str = " B";
  389. double num = len;
  390. double num2 = 1024.0;
  391. if (len >= num2)
  392. {
  393. num = len / num2;
  394. str = " KB";
  395. }
  396. if (num > num2)
  397. {
  398. num /= num2;
  399. str = " MB";
  400. }
  401. if (num > num2)
  402. {
  403. num /= num2;
  404. str = " GB";
  405. }
  406. if (num - Math.Truncate(num) == 0.0)
  407. {
  408. result = num.ToString("F2") + str;
  409. }
  410. else
  411. {
  412. result = num.ToString("F2") + str;
  413. }
  414. }
  415. return result;
  416. }
  417. public static string GetFileSize(int len)
  418. {
  419. return GetFileSize(len, "F2");
  420. }
  421. public static IList<FileInfo> GetFiles(string folder, string extension)
  422. {
  423. return GetFiles(folder, new string[]
  424. {
  425. extension
  426. });
  427. }
  428. public static string GetFileSavaPath(string fileName)
  429. {
  430. string directory = Path.GetDirectoryName(fileName); //文件所在路径
  431. string filename = Path.GetFileNameWithoutExtension(fileName); //文件名
  432. string extension = Path.GetExtension(fileName); //文件后缀 带点(.)
  433. int counter = 1;
  434. string newFilename = string.Format("{0}{1}", filename, extension); //文件名+后缀
  435. string newFullPath = Path.Combine(directory, newFilename);
  436. while (File.Exists(newFullPath)) //如果文件存在,如果存在count+1,继续循环
  437. {
  438. newFilename = string.Format("{0}({1}){2}", filename, counter, extension); //文件名+(count)+后缀
  439. newFullPath = Path.Combine(directory, newFilename); //保存路径
  440. counter++; //count+1
  441. }
  442. return newFullPath;
  443. }
  444. public static IList<FileInfo> GetFiles(string folder, string[] extensions)
  445. {
  446. string[] files = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories);
  447. return (from file in files
  448. let extension = Path.GetExtension(file)
  449. where extension != null && extensions.Contains(extension.ToLower())
  450. select new FileInfo(file)).ToList();
  451. }
  452. public static bool IsValid(string file)
  453. {
  454. bool result;
  455. if (file.IsInvalid())
  456. {
  457. result = false;
  458. }
  459. else if (!File.Exists(file))
  460. {
  461. result = false;
  462. }
  463. else
  464. {
  465. FileInfo fileInfo = new FileInfo(file);
  466. result = (fileInfo.Length > 0L);
  467. }
  468. return result;
  469. }
  470. public static bool IsValidDictory(string path)
  471. {
  472. return !path.IsInvalid() && Directory.Exists(path);
  473. }
  474. public static byte[] ReadFileHead(string filePath, int index = 4)
  475. {
  476. byte[] result;
  477. using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  478. {
  479. byte[] array = new byte[index];
  480. fileStream.Read(array, 0, index);
  481. result = array;
  482. }
  483. return result;
  484. }
  485. public static string FilterInvalidFileName(string oriName)
  486. {
  487. return _InvalidChars.Aggregate(oriName, (string current, char invalidChar) => current.Replace(invalidChar.ToString(), string.Empty));
  488. }
  489. public static bool IsFileInUsing(string path)
  490. {
  491. bool result = true;
  492. try
  493. {
  494. using (new FileStream(path, FileMode.Open))
  495. {
  496. result = false;
  497. }
  498. }
  499. catch
  500. {
  501. }
  502. return result;
  503. }
  504. public static bool InputPathIsValid(string path)
  505. {
  506. return IsPositiveNumber(path) && IsHasUninvalidPathChars(path);
  507. }
  508. private static bool IsPositiveNumber(string path)
  509. {
  510. return Regex.IsMatch(path, "^[a-zA-Z]:\\\\[^\\/\\:\\*\\?\\\"\\<\\>\\|\\,]+$", RegexOptions.IgnoreCase);
  511. }
  512. private static bool IsHasUninvalidPathChars(string path)
  513. {
  514. return !Path.GetInvalidPathChars().Any(new Func<char, bool>(path.Contains<char>));
  515. }
  516. private static readonly object _sync = new object();
  517. private static readonly char[] InvalidPathChars = new char[]
  518. {
  519. '"',
  520. '<',
  521. '>',
  522. '|',
  523. '\0',
  524. '\u0001',
  525. '\u0002',
  526. '\u0003',
  527. '\u0004',
  528. '\u0005',
  529. '\u0006',
  530. '\a',
  531. '\b',
  532. '\t',
  533. '\n',
  534. '\v',
  535. '\f',
  536. '\r',
  537. '\u000e',
  538. '\u000f',
  539. '\u0010',
  540. '\u0011',
  541. '\u0012',
  542. '\u0013',
  543. '\u0014',
  544. '\u0015',
  545. '\u0016',
  546. '\u0017',
  547. '\u0018',
  548. '\u0019',
  549. '\u001a',
  550. '\u001b',
  551. '\u001c',
  552. '\u001d',
  553. '\u001e',
  554. '\u001f',
  555. '*',
  556. '?',
  557. ':'
  558. };
  559. public static void ArgumentNotNull(object value, string argumentName)
  560. {
  561. if (value == null)
  562. {
  563. throw new ArgumentNullException(argumentName, $"参数{argumentName}不能为NULL");
  564. }
  565. }
  566. // Token: 0x0600027D RID: 637 RVA: 0x0000BDCC File Offset: 0x00009FCC
  567. public static void ArgumentNotNullOrEmpty(string value, string argumentName)
  568. {
  569. if (value.IsNullOrEmptyOrWhiteSpace())
  570. {
  571. throw new ArgumentNullException(argumentName, $"参数{argumentName}不能为NULL或者为空");
  572. }
  573. }
  574. private static readonly char[] _InvalidChars = Path.GetInvalidFileNameChars();
  575. }
  576. }