FileHelperCore.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Threading.Tasks;
  7. namespace TEAMModelOS.SDK.Helper.Common.FileHelper
  8. {
  9. /// <summary>
  10. /// Describe:文件帮助类
  11. /// </summary>
  12. public class FileHelperCore
  13. {
  14. private static IWebHostEnvironment _hostingEnvironment = new HttpContextAccessor().HttpContext.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
  15. /// <summary>
  16. /// 目录分隔符
  17. /// windows "\" OSX and Linux "/"
  18. /// </summary>
  19. private static string DirectorySeparatorChar = Path.DirectorySeparatorChar.ToString();
  20. /// <summary>
  21. /// 包含应用程序的目录的绝对路径
  22. /// </summary>
  23. private static string _ContentRootPath = _hostingEnvironment.ContentRootPath;
  24. #region 检测指定路径是否存在
  25. /// <summary>
  26. /// 检测指定路径是否存在
  27. /// </summary>
  28. /// <param name="path">路径</param>
  29. /// <returns></returns>
  30. public static bool IsExist(string path)
  31. {
  32. return IsDirectory(MapPath(path)) ? Directory.Exists(MapPath(path)) : File.Exists(MapPath(path));
  33. }
  34. /// <summary>
  35. /// 检测指定路径是否存在(异步方式)
  36. /// </summary>
  37. /// <param name="path">路径</param>
  38. /// <returns></returns>
  39. public static async Task<bool> IsExistAsync(string path)
  40. {
  41. return await Task.Run(() => IsDirectory(MapPath(path)) ? Directory.Exists(MapPath(path)) : File.Exists(MapPath(path)));
  42. }
  43. #endregion
  44. #region 检测目录是否为空
  45. /// <summary>
  46. /// 检测目录是否为空
  47. /// </summary>
  48. /// <param name="path">路径</param>
  49. /// <returns></returns>
  50. public static bool IsEmptyDirectory(string path)
  51. {
  52. return Directory.GetFiles(MapPath(path)).Length <= 0 && Directory.GetDirectories(MapPath(path)).Length <= 0;
  53. }
  54. /// <summary>
  55. /// 检测目录是否为空
  56. /// </summary>
  57. /// <param name="path">路径</param>
  58. /// <returns></returns>
  59. public static async Task<bool> IsEmptyDirectoryAsync(string path)
  60. {
  61. return await Task.Run(() => Directory.GetFiles(MapPath(path)).Length <= 0 && Directory.GetDirectories(MapPath(path)).Length <= 0);
  62. }
  63. #endregion
  64. #region 创建目录
  65. /// <summary>
  66. /// 创建目录
  67. /// </summary>
  68. /// <param name="path">路径</param>
  69. public static void CreateFiles(string path)
  70. {
  71. try
  72. {
  73. if (IsDirectory(MapPath(path)))
  74. Directory.CreateDirectory(MapPath(path));
  75. else
  76. File.Create(MapPath(path)).Dispose();
  77. }
  78. catch
  79. {
  80. throw;
  81. }
  82. }
  83. #endregion
  84. #region 删除文件或目录
  85. /// <summary>
  86. /// 删除目录或文件
  87. /// </summary>
  88. /// <param name="path">路径</param>
  89. public static void DeleteFiles(string path)
  90. {
  91. try
  92. {
  93. if (IsExist(path))
  94. {
  95. if (IsDirectory(MapPath(path)))
  96. Directory.Delete(MapPath(path));
  97. else
  98. File.Delete(MapPath(path));
  99. }
  100. }
  101. catch
  102. {
  103. throw;
  104. }
  105. }
  106. /// <summary>
  107. /// 清空目录下所有文件及子目录,依然保留该目录
  108. /// </summary>
  109. /// <param name="path"></param>
  110. public static void ClearDirectory(string path)
  111. {
  112. if (IsExist(path))
  113. {
  114. //目录下所有文件
  115. string[] files = Directory.GetFiles(MapPath(path));
  116. foreach (var file in files)
  117. {
  118. DeleteFiles(file);
  119. }
  120. //目录下所有子目录
  121. string[] directorys = Directory.GetDirectories(MapPath(path));
  122. foreach (var dir in directorys)
  123. {
  124. DeleteFiles(dir);
  125. }
  126. }
  127. }
  128. #endregion
  129. #region 判断文件是否为隐藏文件(系统独占文件)
  130. /// <summary>
  131. /// 检测文件或文件夹是否为隐藏文件
  132. /// </summary>
  133. /// <param name="path">路径</param>
  134. /// <returns></returns>
  135. public static bool IsHiddenFile(string path)
  136. {
  137. return IsDirectory(MapPath(path)) ? InspectHiddenFile(new DirectoryInfo(MapPath(path))) : InspectHiddenFile(new FileInfo(MapPath(path)));
  138. }
  139. /// <summary>
  140. /// 检测文件或文件夹是否为隐藏文件(异步方式)
  141. /// </summary>
  142. /// <param name="path">路径</param>
  143. /// <returns></returns>
  144. public static async Task<bool> IsHiddenFileAsync(string path)
  145. {
  146. return await Task.Run(() => IsDirectory(MapPath(path)) ? InspectHiddenFile(new DirectoryInfo(MapPath(path))) : InspectHiddenFile(new FileInfo(MapPath(path))));
  147. }
  148. /// <summary>
  149. /// 私有方法 文件是否为隐藏文件(系统独占文件)
  150. /// </summary>
  151. /// <param name="fileSystemInfo"></param>
  152. /// <returns></returns>
  153. private static bool InspectHiddenFile(FileSystemInfo fileSystemInfo)
  154. {
  155. if (fileSystemInfo.Name.StartsWith("."))
  156. {
  157. return true;
  158. }
  159. else if (fileSystemInfo.Exists &&
  160. ((fileSystemInfo.Attributes & FileAttributes.Hidden) != 0 ||
  161. (fileSystemInfo.Attributes & FileAttributes.System) != 0))
  162. {
  163. return true;
  164. }
  165. return false;
  166. }
  167. #endregion
  168. #region 文件操作
  169. #region 复制文件
  170. /// <summary>
  171. /// 复制文件内容到目标文件夹
  172. /// </summary>
  173. /// <param name="sourcePath">源文件</param>
  174. /// <param name="targetPath">目标文件夹</param>
  175. /// <param name="isOverWrite">是否可以覆盖</param>
  176. public static void Copy(string sourcePath, string targetPath, bool isOverWrite = true)
  177. {
  178. File.Copy(MapPath(sourcePath), MapPath(targetPath) + GetFileName(sourcePath), isOverWrite);
  179. }
  180. /// <summary>
  181. /// 复制文件内容到目标文件夹
  182. /// </summary>
  183. /// <param name="sourcePath">源文件</param>
  184. /// <param name="targetPath">目标文件夹</param>
  185. /// <param name="newName">新文件名称</param>
  186. /// <param name="isOverWrite">是否可以覆盖</param>
  187. public static void Copy(string sourcePath, string targetPath, string newName, bool isOverWrite = true)
  188. {
  189. File.Copy(MapPath(sourcePath), MapPath(targetPath) + newName, isOverWrite);
  190. }
  191. #endregion
  192. #region 移动文件
  193. /// <summary>
  194. /// 移动文件到目标目录
  195. /// </summary>
  196. /// <param name="sourcePath">源文件</param>
  197. /// <param name="targetPath">目标目录</param>
  198. public static void Move(string sourcePath, string targetPath)
  199. {
  200. string sourceFileName = GetFileName(sourcePath);
  201. //如果目标目录不存在则创建
  202. if (IsExist(targetPath))
  203. {
  204. CreateFiles(targetPath);
  205. }
  206. else
  207. {
  208. //如果目标目录存在同名文件则删除
  209. if (IsExist(Path.Combine(MapPath(targetPath), sourceFileName)))
  210. {
  211. DeleteFiles(Path.Combine(MapPath(targetPath), sourceFileName));
  212. }
  213. }
  214. File.Move(MapPath(sourcePath), Path.Combine(MapPath(targetPath), sourceFileName));
  215. }
  216. #endregion
  217. /// <summary>
  218. /// 获取文件名和扩展名
  219. /// </summary>
  220. /// <param name="path">文件路径</param>
  221. /// <returns></returns>
  222. public static string GetFileName(string path)
  223. {
  224. return Path.GetFileName(MapPath(path));
  225. }
  226. /// <summary>
  227. /// 获取文件名不带扩展名
  228. /// </summary>
  229. /// <param name="path">文件路径</param>
  230. /// <returns></returns>
  231. public static string GetFileNameWithOutExtension(string path)
  232. {
  233. return Path.GetFileNameWithoutExtension(MapPath(path));
  234. }
  235. /// <summary>
  236. /// 获取文件扩展名
  237. /// </summary>
  238. /// <param name="path">文件路径</param>
  239. /// <returns></returns>
  240. public static string GetFileExtension(string path)
  241. {
  242. return Path.GetExtension(MapPath(path));
  243. }
  244. #endregion
  245. #region 获取文件绝对路径
  246. /// <summary>
  247. /// 获取文件绝对路径
  248. /// </summary>
  249. /// <param name="path">文件路径</param>
  250. /// <returns></returns>
  251. public static string MapPath(string path)
  252. {
  253. return Path.Combine(_ContentRootPath, path.TrimStart('~', '/').Replace("/", DirectorySeparatorChar));
  254. }
  255. /// <summary>
  256. /// 获取文件绝对路径(异步方式)
  257. /// </summary>
  258. /// <param name="path">文件路径</param>
  259. /// <returns></returns>
  260. public static async Task<string> MapPathAsync(string path)
  261. {
  262. return await Task.Run(() => Path.Combine(_ContentRootPath, path.TrimStart('~', '/').Replace("/", DirectorySeparatorChar)));
  263. }
  264. /// <summary>
  265. /// 是否为目录或文件夹
  266. /// </summary>
  267. /// <param name="path">路径</param>
  268. /// <returns></returns>
  269. public static bool IsDirectory(string path)
  270. {
  271. if (path.EndsWith(DirectorySeparatorChar))
  272. return true;
  273. else
  274. return false;
  275. }
  276. #endregion
  277. #region 物理路径转虚拟路径
  278. public static string PhysicalToVirtual(string physicalPath)
  279. {
  280. return physicalPath.Replace(_ContentRootPath, "").Replace(DirectorySeparatorChar, "/");
  281. }
  282. #endregion
  283. #region 文件格式
  284. /// <summary>
  285. /// 是否可添加水印
  286. /// </summary>
  287. /// <param name="_fileExt">文件扩展名,不含“.”</param>
  288. /// <returns></returns>
  289. public static bool IsCanWater(string _fileExt)
  290. {
  291. var images = new List<string> { "jpg", "jpeg" };
  292. if (images.Contains(_fileExt.ToLower())) return true;
  293. return false;
  294. }
  295. /// <summary>
  296. /// 是否为图片
  297. /// </summary>
  298. /// <param name="_fileExt">文件扩展名,不含“.”</param>
  299. /// <returns></returns>
  300. public static bool IsImage(string _fileExt)
  301. {
  302. var images = new List<string> { "bmp", "gif", "jpg", "jpeg", "png" };
  303. if (images.Contains(_fileExt.ToLower())) return true;
  304. return false;
  305. }
  306. /// <summary>
  307. /// 是否为视频
  308. /// </summary>
  309. /// <param name="_fileExt">文件扩展名,不含“.”</param>
  310. /// <returns></returns>
  311. public static bool IsVideos(string _fileExt)
  312. {
  313. var videos = new List<string> { "rmvb", "mkv", "ts", "wma", "avi", "rm", "mp4", "flv", "mpeg", "mov", "3gp", "mpg" };
  314. if (videos.Contains(_fileExt.ToLower())) return true;
  315. return false;
  316. }
  317. /// <summary>
  318. /// 是否为音频
  319. /// </summary>
  320. /// <param name="_fileExt">文件扩展名,不含“.”</param>
  321. /// <returns></returns>
  322. public static bool IsMusics(string _fileExt)
  323. {
  324. var musics = new List<string> { "mp3", "wav" };
  325. if (musics.Contains(_fileExt.ToLower())) return true;
  326. return false;
  327. }
  328. /// <summary>
  329. /// 是否为文档
  330. /// </summary>
  331. /// <param name="_fileExt">文件扩展名,不含“.”</param>
  332. /// <returns></returns>
  333. public static bool IsDocument(string _fileExt)
  334. {
  335. var documents = new List<string> { "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", "pdf" };
  336. if (documents.Contains(_fileExt.ToLower())) return true;
  337. return false;
  338. }
  339. #endregion
  340. #region 文件图标
  341. public static string FindFileIcon(string fileExt)
  342. {
  343. if (IsImage(fileExt))
  344. return "fa fa-image";
  345. if (IsVideos(fileExt))
  346. return "fa fa-film";
  347. if (IsMusics(fileExt))
  348. return "fa fa-music";
  349. if (IsDocument(fileExt))
  350. switch (fileExt.ToLower())
  351. {
  352. case ".xls":
  353. case ".xlsx":
  354. return "fa fa-file-excel-o";
  355. case ".ppt":
  356. case ".pptx":
  357. return "fa fa-file-powerpoint-o";
  358. case ".pdf":
  359. return "fa fa-file-pdf-o";
  360. case ".txt":
  361. return "fa fa-file-text-o";
  362. default:
  363. return "fa fa-file-word-o";
  364. }
  365. if (fileExt.ToLower() .Equals( "zip") || fileExt.ToLower().Equals("rar)"))
  366. return "fa fa-file-zip-o";
  367. else
  368. return "fa fa-file";
  369. }
  370. #endregion
  371. #region 文件大小转换
  372. /// <summary>
  373. /// 文件大小转为B、KB、MB、GB...
  374. /// </summary>
  375. /// <param name="size"></param>
  376. /// <returns></returns>
  377. public static string FileSizeTransf(long size)
  378. {
  379. String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
  380. long mod = 1024;
  381. int i = 0;
  382. while (size > mod)
  383. {
  384. size /= mod;
  385. i++;
  386. }
  387. return size + units[i];
  388. }
  389. #endregion
  390. #region 获取目录下所有文件
  391. public static List<FilesInfo> FindFiles(string path, string staticFiles = "/wwwroot")
  392. {
  393. string[] folders = Directory.GetDirectories(MapPath(path), "*", SearchOption.AllDirectories);
  394. var Files = new List<FilesInfo>();
  395. foreach (var folder in folders)
  396. {
  397. foreach (var fsi in new DirectoryInfo(folder).GetFiles())
  398. {
  399. Files.Add(new FilesInfo()
  400. {
  401. Name = fsi.Name,
  402. FullName = fsi.FullName,
  403. FileExt = fsi.Extension,
  404. FileOriginalSize = fsi.Length,
  405. FileSize = FileSizeTransf(fsi.Length),
  406. FileIcon = FindFileIcon(fsi.Extension.Remove(0, 1)),
  407. FileName = PhysicalToVirtual(fsi.FullName).Replace(staticFiles, ""),
  408. FileStyle = IsImage(fsi.Extension.Remove(0, 1)) ? "images" :
  409. IsDocument(fsi.Extension.Remove(0, 1)) ? "documents" :
  410. IsVideos(fsi.Extension.Remove(0, 1)) ? "videos" :
  411. IsMusics(fsi.Extension.Remove(0, 1)) ? "musics" : "others",
  412. CreateDate = fsi.CreationTime,
  413. LastWriteDate = fsi.LastWriteTime,
  414. LastAccessDate = fsi.LastAccessTime
  415. });
  416. }
  417. }
  418. return Files;
  419. }
  420. /// <summary>
  421. /// 获得指定文件夹下面的所有文件
  422. /// </summary>
  423. /// <param name="path"></param>
  424. /// <param name="staticFiles"></param>
  425. /// <returns></returns>
  426. public static List<FilesInfo> ResolveFileInfo(string path, string staticFiles = "/wwwroot")
  427. {
  428. var foldersPath = MapPath(path);
  429. var Files = new List<FilesInfo>();
  430. foreach (var fsi in new DirectoryInfo(foldersPath).GetFiles())
  431. {
  432. Files.Add(new FilesInfo()
  433. {
  434. Name = fsi.Name,
  435. FullName = fsi.FullName,
  436. FileExt = fsi.Extension,
  437. FileOriginalSize = fsi.Length,
  438. FileSize = FileSizeTransf(fsi.Length),
  439. FileIcon = FindFileIcon(fsi.Extension.Remove(0, 1)),
  440. FileName = PhysicalToVirtual(fsi.FullName).Replace(staticFiles, ""),
  441. FileStyle = IsImage(fsi.Extension.Remove(0, 1)) ? "images" :
  442. IsDocument(fsi.Extension.Remove(0, 1)) ? "documents" :
  443. IsVideos(fsi.Extension.Remove(0, 1)) ? "videos" :
  444. IsMusics(fsi.Extension.Remove(0, 1)) ? "musics" : "others",
  445. CreateDate = fsi.CreationTime,
  446. LastWriteDate = fsi.LastWriteTime,
  447. LastAccessDate = fsi.LastAccessTime
  448. });
  449. }
  450. return Files;
  451. }
  452. #endregion
  453. }
  454. public class FilesInfo
  455. {
  456. /// <summary>
  457. /// 文件名称
  458. /// </summary>
  459. public string Name { get; set; }
  460. /// <summary>
  461. /// 文件物理路径
  462. /// </summary>
  463. public string FullName { get; set; }
  464. /// <summary>
  465. /// 扩展名
  466. /// </summary>
  467. public string FileExt { get; set; }
  468. /// <summary>
  469. /// 原始大小(字节)
  470. /// </summary>
  471. public long FileOriginalSize { get; set; }
  472. /// <summary>
  473. /// 文件大小
  474. /// </summary>
  475. public string FileSize { get; set; }
  476. /// <summary>
  477. /// 文件虚拟路径
  478. /// </summary>
  479. public string FileName { get; set; }
  480. /// <summary>
  481. /// 文件类型
  482. /// </summary>
  483. public string FileStyle { get; set; }
  484. /// <summary>
  485. /// 文件图标
  486. /// </summary>
  487. public string FileIcon { get; set; }
  488. /// <summary>
  489. /// 创建时间
  490. /// </summary>
  491. public DateTime CreateDate { get; set; }
  492. /// <summary>
  493. /// 最后修改时间
  494. /// </summary>
  495. public DateTime LastWriteDate { get; set; }
  496. /// <summary>
  497. /// 最后访问时间
  498. /// </summary>
  499. public DateTime LastAccessDate { get; set; }
  500. }
  501. }