FileHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Data;
  7. namespace Ant.Service.Common
  8. {
  9. /// <summary>
  10. /// 文件帮助类
  11. /// add 作者: 季健国 QQ:181589805 by 2016-06-11
  12. /// </summary>
  13. public class FileHelper
  14. {
  15. #region 获取文件到集合中
  16. /// <summary>
  17. /// 读取指定位置文件列表到集合中
  18. /// </summary>
  19. /// <param name="Path">指定路径</param>
  20. /// <returns></returns>
  21. public static DataTable GetFileTable(string Path)
  22. {
  23. DataTable dt = new DataTable();
  24. dt.Columns.Add("name", typeof(string));
  25. dt.Columns.Add("ext",typeof(string));
  26. dt.Columns.Add("size", typeof(string));
  27. dt.Columns.Add("time",typeof(DateTime));
  28. DirectoryInfo dirinfo = new DirectoryInfo(Path);
  29. FileInfo fi;
  30. DirectoryInfo dir;
  31. string FileName = string.Empty, FileExt = string.Empty, FileSize = string.Empty;
  32. DateTime FileModify;
  33. try
  34. {
  35. foreach (FileSystemInfo fsi in dirinfo.GetFileSystemInfos())
  36. {
  37. if (fsi is FileInfo)
  38. {
  39. fi = (FileInfo)fsi;
  40. //获取文件名称
  41. FileName = fi.Name;
  42. //获取文件扩展名
  43. FileExt = fi.Extension;
  44. //获取文件大小
  45. FileSize = GetDiyFileSize(fi);
  46. //获取文件最后修改时间
  47. FileModify = fi.LastWriteTime;
  48. }
  49. else
  50. {
  51. dir = (DirectoryInfo)fsi;
  52. //获取目录名
  53. FileName = dir.Name;
  54. //获取目录最后修改时间
  55. FileModify = dir.LastWriteTime;
  56. //设置目录文件为文件夹
  57. FileExt = "文件夹";
  58. }
  59. DataRow dr = dt.NewRow();
  60. dr["name"] = FileName;
  61. dr["ext"] = FileExt;
  62. dr["size"] = FileSize;
  63. dr["time"] = FileModify;
  64. dt.Rows.Add(dr);
  65. }
  66. }
  67. catch{
  68. throw;
  69. }
  70. return dt;
  71. }
  72. #endregion
  73. #region 检测指定路径是否存在
  74. /// <summary>
  75. /// 检测指定路径是否存在
  76. /// </summary>
  77. /// <param name="Path">目录的绝对路径</param>
  78. public static bool IsExistDirectory(string Path)
  79. {
  80. return Directory.Exists(Path);
  81. }
  82. #endregion
  83. #region 检测指定文件是否存在,如果存在则返回true
  84. /// <summary>
  85. /// 检测指定文件是否存在,如果存在则返回true
  86. /// </summary>
  87. /// <param name="filePath">文件的绝对路径</param>
  88. public static bool IsExistFile(string filePath)
  89. {
  90. return File.Exists(filePath);
  91. }
  92. #endregion
  93. #region 创建文件夹
  94. /// <summary>
  95. /// 创建文件夹
  96. /// </summary>
  97. /// <param name="FolderPath">文件夹的绝对路径</param>
  98. public static void CreateFolder(string FolderPath)
  99. {
  100. if (!IsExistDirectory(FolderPath))
  101. {
  102. Directory.CreateDirectory(FolderPath);
  103. }
  104. }
  105. #endregion
  106. #region 判断上传文件后缀名
  107. /// <summary>
  108. /// 判断上传文件后缀名
  109. /// </summary>
  110. /// <param name="strExtension">后缀名</param>
  111. public static bool IsCanEdit(string strExtension)
  112. {
  113. strExtension = strExtension.ToLower();
  114. if (strExtension.LastIndexOf(".") >= 0)
  115. {
  116. strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
  117. }
  118. else
  119. {
  120. strExtension = ".txt";
  121. }
  122. string[] strArray = new string[] { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
  123. for (int i = 0; i < strArray.Length; i++)
  124. {
  125. if (strExtension.Equals(strArray[i]))
  126. {
  127. return true;
  128. }
  129. }
  130. return false;
  131. }
  132. public static bool IsSafeName(string strExtension)
  133. {
  134. strExtension = strExtension.ToLower();
  135. if (strExtension.LastIndexOf(".") >= 0)
  136. {
  137. strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
  138. }
  139. else
  140. {
  141. strExtension = ".txt";
  142. }
  143. string[] strArray = new string[] { ".jpg", ".gif", ".png" };
  144. for (int i = 0; i < strArray.Length; i++)
  145. {
  146. if (strExtension.Equals(strArray[i]))
  147. {
  148. return true;
  149. }
  150. }
  151. return false;
  152. }
  153. public static bool IsZipName(string strExtension)
  154. {
  155. strExtension = strExtension.ToLower();
  156. if (strExtension.LastIndexOf(".") >= 0)
  157. {
  158. strExtension = strExtension.Substring(strExtension.LastIndexOf("."));
  159. }
  160. else
  161. {
  162. strExtension = ".txt";
  163. }
  164. string[] strArray = new string[] { ".zip", ".rar" };
  165. for (int i = 0; i < strArray.Length; i++)
  166. {
  167. if (strExtension.Equals(strArray[i]))
  168. {
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. #endregion
  175. #region 创建文件夹
  176. /// <summary>
  177. /// 创建文件夹
  178. /// </summary>
  179. /// <param name="fileName">文件的绝对路径</param>
  180. public static void CreateSuffic(string filename)
  181. {
  182. try
  183. {
  184. if (!Directory.Exists(filename))
  185. {
  186. Directory.CreateDirectory(filename);
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. throw ex;
  192. }
  193. }
  194. /// <summary>
  195. /// 创建文件夹
  196. /// </summary>
  197. /// <param name="fileName">文件的绝对路径</param>
  198. public static void CreateFiles(string fileName)
  199. {
  200. try
  201. {
  202. //判断文件是否存在,不存在创建该文件
  203. if (!IsExistFile(fileName))
  204. {
  205. FileInfo file = new FileInfo(fileName);
  206. FileStream fs = file.Create();
  207. fs.Close();
  208. }
  209. }
  210. catch (Exception ex)
  211. {
  212. throw ex;
  213. }
  214. }
  215. /// <summary>
  216. /// 创建一个文件,并将字节流写入文件。
  217. /// </summary>
  218. /// <param name="filePath">文件的绝对路径</param>
  219. /// <param name="buffer">二进制流数据</param>
  220. public static void CreateFile(string filePath, byte[] buffer)
  221. {
  222. try
  223. {
  224. //判断文件是否存在,不存在创建该文件
  225. if (!IsExistFile(filePath))
  226. {
  227. FileInfo file = new FileInfo(filePath);
  228. FileStream fs = file.Create();
  229. fs.Write(buffer, 0, buffer.Length);
  230. fs.Close();
  231. }
  232. else
  233. {
  234. File.WriteAllBytes(filePath, buffer);
  235. }
  236. }
  237. catch (Exception ex)
  238. {
  239. throw ex;
  240. }
  241. }
  242. #endregion
  243. #region 将文件移动到指定目录
  244. /// <summary>
  245. /// 将文件移动到指定目录
  246. /// </summary>
  247. /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
  248. /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
  249. public static void Move(string sourceFilePath, string descDirectoryPath)
  250. {
  251. string sourceName = GetFileName(sourceFilePath);
  252. if (IsExistDirectory(descDirectoryPath))
  253. {
  254. //如果目标中存在同名文件,则删除
  255. if (IsExistFile(descDirectoryPath + "\\" + sourceFilePath))
  256. {
  257. DeleteFile(descDirectoryPath + "\\" + sourceFilePath);
  258. }
  259. else
  260. {
  261. //将文件移动到指定目录
  262. File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFilePath);
  263. }
  264. }
  265. }
  266. #endregion
  267. /// <summary>
  268. /// 将源文件的内容复制到目标文件中
  269. /// </summary>
  270. /// <param name="sourceFilePath">源文件的绝对路径</param>
  271. /// <param name="descDirectoryPath">目标文件的绝对路径</param>
  272. public static void Copy(string sourceFilePath, string descDirectoryPath)
  273. {
  274. File.Copy(sourceFilePath, descDirectoryPath, true);
  275. }
  276. /// <summary>
  277. /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
  278. /// </summary>
  279. /// <param name="filePath">文件的绝对路径</param>
  280. public static string GetFileName(string filePath)
  281. {
  282. FileInfo file = new FileInfo(filePath);
  283. return file.Name;
  284. }
  285. /// <summary>
  286. /// 获取文件的后缀名
  287. /// </summary>
  288. /// <param name="filePath">文件的绝对路径</param>
  289. public static string GetExtension(string filePath)
  290. {
  291. FileInfo file = new FileInfo(filePath);
  292. return file.Extension;
  293. }
  294. /// <summary>
  295. /// 删除指定文件
  296. /// </summary>
  297. /// <param name="filePath">文件的绝对路径</param>
  298. public static void DeleteFile(string filePath)
  299. {
  300. if (IsExistFile(filePath))
  301. {
  302. File.Delete(filePath);
  303. }
  304. }
  305. /// <summary>
  306. /// 删除指定目录及其所有子目录
  307. /// </summary>
  308. /// <param name="directoryPath">文件的绝对路径</param>
  309. public static void DeleteDirectory(string directoryPath)
  310. {
  311. if (IsExistDirectory(directoryPath))
  312. {
  313. Directory.Delete(directoryPath);
  314. }
  315. }
  316. /// <summary>
  317. /// 清空指定目录下所有文件及子目录,但该目录依然保存.
  318. /// </summary>
  319. /// <param name="directoryPath">指定目录的绝对路径</param>
  320. public static void ClearDirectory(string directoryPath)
  321. {
  322. if (IsExistDirectory(directoryPath))
  323. {
  324. //删除目录中所有的文件
  325. string[] fileNames = GetFileNames(directoryPath);
  326. for (int i = 0; i < fileNames.Length; i++)
  327. {
  328. DeleteFile(fileNames[i]);
  329. }
  330. //删除目录中所有的子目录
  331. string[] directoryNames = GetDirectories(directoryPath);
  332. for (int i = 0; i < directoryNames.Length; i++)
  333. {
  334. DeleteDirectory(directoryNames[i]);
  335. }
  336. }
  337. }
  338. #region 剪切 粘贴
  339. /// <summary>
  340. /// 剪切文件
  341. /// </summary>
  342. /// <param name="source">原路径</param>
  343. /// <param name="destination">新路径</param>
  344. public bool FileMove(string source, string destination)
  345. {
  346. bool ret = false;
  347. FileInfo file_s = new FileInfo(source);
  348. FileInfo file_d = new FileInfo(destination);
  349. if (file_s.Exists)
  350. {
  351. if (!file_d.Exists)
  352. {
  353. file_s.MoveTo(destination);
  354. ret = true;
  355. }
  356. }
  357. if (ret == true)
  358. {
  359. //Response.Write("<script>alert('剪切文件成功!');</script>");
  360. }
  361. else
  362. {
  363. //Response.Write("<script>alert('剪切文件失败!');</script>");
  364. }
  365. return ret;
  366. }
  367. #endregion
  368. /// <summary>
  369. /// 检测指定目录是否为空
  370. /// </summary>
  371. /// <param name="directoryPath">指定目录的绝对路径</param>
  372. public static bool IsEmptyDirectory(string directoryPath)
  373. {
  374. try
  375. {
  376. //判断文件是否存在
  377. string[] fileNames = GetFileNames(directoryPath);
  378. if (fileNames.Length > 0)
  379. {
  380. return false;
  381. }
  382. //判断是否存在文件夹
  383. string[] directoryNames = GetDirectories(directoryPath);
  384. if (directoryNames.Length > 0)
  385. {
  386. return false;
  387. }
  388. return true;
  389. }
  390. catch //(Exception ex)
  391. {
  392. return true;
  393. }
  394. }
  395. #region 获取指定目录中所有文件列表
  396. /// <summary>
  397. /// 获取指定目录中所有文件列表
  398. /// </summary>
  399. /// <param name="directoryPath">指定目录的绝对路径</param>
  400. public static string[] GetFileNames(string directoryPath)
  401. {
  402. if (!IsExistDirectory(directoryPath))
  403. {
  404. throw new FileNotFoundException();
  405. }
  406. return Directory.GetFiles(directoryPath);
  407. }
  408. #endregion
  409. #region 获取指定目录中的子目录列表
  410. /// <summary>
  411. /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法
  412. /// </summary>
  413. /// <param name="directoryPath">指定目录的绝对路径</param>
  414. public static string[] GetDirectories(string directoryPath)
  415. {
  416. try
  417. {
  418. return Directory.GetDirectories(directoryPath);
  419. }
  420. catch (Exception ex)
  421. {
  422. throw ex;
  423. }
  424. }
  425. /// <summary>
  426. /// 获取指定目录及子目录中所有子目录列表
  427. /// </summary>
  428. /// <param name="directoryPath">指定目录的绝对路径</param>
  429. /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
  430. /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
  431. /// <param name="isSearchChild">是否搜索子目录</param>
  432. public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
  433. {
  434. try
  435. {
  436. if (isSearchChild)
  437. {
  438. return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
  439. }
  440. else
  441. {
  442. return Directory.GetDirectories(directoryPath,searchPattern, SearchOption.TopDirectoryOnly);
  443. }
  444. }
  445. catch (Exception ex)
  446. {
  447. throw ex;
  448. }
  449. }
  450. #endregion
  451. #region 获取一个文件的长度
  452. /// <summary>
  453. /// 获取文件长度,返回字符串 byte kb mb gb
  454. /// </summary>
  455. public static string GetDiyFileSize(FileInfo fi)
  456. {
  457. string FileSize = string.Empty;
  458. //获取文件大小
  459. if (fi.Length < 1024)//小于1KB
  460. {
  461. FileSize = fi.Length.ToString() + "byte";
  462. }
  463. else if (fi.Length > 1024 && fi.Length < 1024 * 1024)//大于1KB小于1MB
  464. {
  465. FileSize = Math.Round(GetFileSizeByKB(fi.Length), 2).ToString() + "KB";
  466. }
  467. else if (fi.Length > 1024 * 1024 && fi.Length < 1024 * 1024 * 1024)//大于1MB小于1GB
  468. {
  469. FileSize = Math.Round(GetFileSizeByMB(fi.Length), 2).ToString() + "MB";
  470. }
  471. else //GB
  472. {
  473. FileSize = Math.Round(GetFileSizeByGB(fi.Length), 2).ToString() + "GB";
  474. }
  475. return FileSize;
  476. }
  477. public static decimal GetDiyFileSize(long Length,out string unit)
  478. {
  479. decimal FileSize = 0m;
  480. unit = string.Empty;
  481. //获取文件大小
  482. if (Length < 1024)//小于1KB
  483. {
  484. FileSize = Length;
  485. unit = "byte";
  486. }
  487. else if (Length > 1024 && Length < 1024 * 1024)//大于1KB小于1MB
  488. {
  489. FileSize = Math.Round(GetFileSizeByKB(Length), 2);
  490. unit = "KB";
  491. }
  492. else if (Length > 1024 * 1024 && Length < 1024 * 1024 * 1024)//大于1MB小于1GB
  493. {
  494. FileSize = Math.Round(GetFileSizeByMB(Length), 2);
  495. unit = "MB";
  496. }
  497. else //GB
  498. {
  499. FileSize = Math.Round(GetFileSizeByGB(Length), 2);
  500. unit = "GB";
  501. }
  502. return FileSize;
  503. }
  504. /// <summary>
  505. /// 获取一个文件的长度,单位为Byte
  506. /// </summary>
  507. /// <param name="filePath">文件的绝对路径</param>
  508. public static long GetFileSize(string filePath)
  509. {
  510. //创建一个文件对象
  511. FileInfo fi = new FileInfo(filePath);
  512. //获取文件的大小
  513. return fi.Length;
  514. }
  515. /// <summary>
  516. /// 获取一个文件的长度,单位为KB
  517. /// </summary>
  518. /// <param name="filelength">byte</param>
  519. public static decimal GetFileSizeByKB(long filelength)
  520. {
  521. return Convert.ToDecimal(filelength) / 1024;
  522. }
  523. /// <summary>
  524. /// 获取一个文件的长度,单位为MB
  525. /// </summary>
  526. /// <param name="filePath">byte</param>
  527. public static decimal GetFileSizeByMB(long filelength)
  528. {
  529. //获取文件的大小
  530. return Convert.ToDecimal(Convert.ToDecimal(filelength / 1024) / 1024);
  531. }
  532. /// <summary>
  533. /// 获取一个文件的长度,单位为GB
  534. /// </summary>
  535. /// <param name="filePath">byte</param>
  536. public static decimal GetFileSizeByGB(long filelength)
  537. {
  538. //获取文件的大小
  539. return Convert.ToDecimal(Convert.ToDecimal(Convert.ToDecimal(filelength / 1024) / 1024) / 1024);
  540. }
  541. #endregion
  542. }
  543. }