FileOperationHelper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using System.Security.Principal;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace SmartCoalApplication.Base.CommTool
  12. {
  13. public static class FileOperationHelper
  14. {
  15. public static string privateKey = "<RSAKeyValue><Modulus>k44zKgQwvGWgeyLzgBpY/0/PIX2MsWz2umEx53G74tz14rmplqtOozM+42TqZgTh3sX/iDTxa/rfhQizZmYIe3HvxkG7F5CGjnNTreQzFZM7odnHtHPK5LZTkXCm8kob6xlZd5w8A+Y5rlWas4dXpSquhEfGCGGENjydWT6Px+U=</Modulus><Exponent>AQAB</Exponent><P>z7F5KyVFLY9qRz4vp5JKTzN510O2csWI8uvTCx8DAt9jkJzTOGJYiFrlT0OIDDujF03fTCwkuBN9JObgAul6Xw==</P><Q>td/8jhHrSmCaunHwPYooDnwbhgnW1ZiXavZp+lXVAcZrIoGkzQUiSI2N1c6Jj2vPy0JYcYlGRsTQKJ0Nsa/sOw==</Q><DP>Ovh5HvcGHVmLI49UmI/A6ZwEDEr9krjjmZW75nx3rmkfLABbOLczzAOC+G6EQnTsacGClW4zPtDJx6CGGk2QoQ==</DP><DQ>RFGRIyTkB5pmROcL4XIGPfqstBr6El4xcsKBaMHZM8N+9wVQDJuDF1HlF41v6uoKskWHx45TUb4Ym0jzne2BhQ==</DQ><InverseQ>agTNLFUFg7tFIA6wOS30JP0wCQSinrWuDRl5SK1l55Rv2ssnWITDBd+5T9IuQwCqu8AWCm2zb06bkppBkY44dw==</InverseQ><D>GsLZiK9F34VW+741B3C/314sJNjOYYdvoBHsqRs5hkWo2rvthAQBuRucNkWhNWuBQ5QJajyf5IOVcl1HnDS5KNOzr0tzEMCm3LqdfS1cf7FAeytAREZd7aZUt4jRh249o5zu6lgCp/ITz3ZX8XX7eMMXq64GoWS55P8oTxawdqk=</D></RSAKeyValue>";
  16. /// <summary>
  17. /// 读取文件内容到字符串
  18. /// </summary>
  19. /// <param name="filepath">文件路径</param>
  20. /// <param name="mode">操作模式</param>
  21. /// <returns></returns>
  22. public static string ReadStringFromFile(string filepath, FileMode mode)
  23. {
  24. try
  25. {
  26. using (FileStream fs = new FileStream(filepath, mode))
  27. {
  28. StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
  29. return sr.ReadToEnd().Trim();
  30. }
  31. }
  32. catch (Exception ex)
  33. {
  34. throw new Exception("", ex);// "文件读取失败", ex);
  35. }
  36. }
  37. /// <summary>
  38. /// 将字符串写入到文件
  39. /// </summary>
  40. /// <param name="strXML">字符串</param>
  41. /// <param name="filePath">文件路径</param>
  42. /// <param name="mode">文件操作模式</param>
  43. /// <returns></returns>
  44. public static bool WriteStringToFile(string strXML, string filePath, FileMode mode)
  45. {
  46. try
  47. {
  48. if (File.Exists(filePath))
  49. {
  50. File.Delete(filePath);
  51. }
  52. FileStream fs = new FileStream(filePath, mode);
  53. byte[] data = System.Text.Encoding.UTF8.GetBytes(strXML);
  54. //开始写入
  55. fs.Write(data, 0, data.Length);
  56. //清空缓冲区、关闭流
  57. fs.Flush();
  58. fs.Close();
  59. return true;
  60. }
  61. catch (Exception ex)
  62. {
  63. throw new Exception("", ex); //("文件写入失败", ex);
  64. }
  65. }
  66. /// <summary>
  67. /// 获取文件夹下所有文件名
  68. /// </summary>
  69. /// <param name="path"></param>
  70. /// <returns></returns>
  71. public static List<string> GetFileList(string path)
  72. {
  73. DirectoryInfo folder = new DirectoryInfo(path);
  74. List<string> files = new List<string>();
  75. foreach (FileInfo file in folder.GetFiles("*.xml"))
  76. {
  77. files.Add(file.Name);
  78. }
  79. return files;
  80. }
  81. /// <summary>
  82. /// 获取文件夹下所有图片
  83. /// </summary>
  84. /// <param name="path"></param>
  85. /// <returns></returns>
  86. public static List<string> GetAllImgList(string path)
  87. {
  88. DirectoryInfo folder = new DirectoryInfo(path);
  89. List<string> files = new List<string>();
  90. files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Where(s => s.ToLower().EndsWith(".jpg") || s.ToLower().EndsWith(".jpeg") || s.ToLower().EndsWith(".ico") || s.ToLower().EndsWith(".png") || s.ToLower().EndsWith(".tif") || s.ToLower().EndsWith(".wmf") || s.ToLower().EndsWith(".bmp")).ToList();
  91. return files;
  92. }
  93. /// <summary>
  94. /// 文件重命名,直到不重名为止
  95. /// </summary>
  96. /// <param name="path"></param>
  97. /// <returns></returns>
  98. public static string GetReNameFile(string path)
  99. {
  100. string newName;
  101. int i = 1;
  102. do
  103. {
  104. newName = "";
  105. newName += Path.GetDirectoryName(path);
  106. newName += "\\" + Path.GetFileNameWithoutExtension(path) + "-" + i + Path.GetExtension(path);
  107. i++;
  108. }
  109. while (File.Exists(newName));
  110. return newName;
  111. }
  112. /// <summary>
  113. /// 获取文件夹内
  114. /// 当前重名文件之后,还有多少个重名的文件
  115. /// </summary>
  116. /// <param name="fileNames"></param>
  117. /// <param name="index"></param>
  118. /// <returns></returns>
  119. public static int GetNumAfterThisFile(string[] fileNames, int index)
  120. {
  121. int num = 0;
  122. for (int y = 0; y < index; y++)
  123. {
  124. if (File.Exists(fileNames[y]))
  125. {
  126. num++;
  127. }
  128. }
  129. return num;
  130. }
  131. /// <summary>
  132. /// 文件重命名
  133. /// </summary>
  134. /// <param name="path"></param>
  135. /// <returns></returns>
  136. public static void reNameFile(string oldPath,string newPath)
  137. {
  138. if (File.Exists(oldPath))
  139. {
  140. // 改名方法
  141. FileInfo fi = new FileInfo(oldPath);
  142. fi.MoveTo(Path.Combine(newPath));
  143. }
  144. }
  145. /// <summary>
  146. /// 目录下所有内容复制
  147. /// </summary>
  148. /// <param name="SourcePath">要Copy的文件</param>
  149. /// <param name="DestinationPath">要复制到哪个地方</param>
  150. /// <param name="overwriteexisting">是否覆盖</param>
  151. /// <returns></returns>
  152. public static bool CopyFile(string SourcePath, string DestinationPath, string dateTimeStr ,bool overwriteexisting)
  153. {
  154. bool ret = false;
  155. try
  156. {
  157. //复制单个文件用的
  158. if (File.Exists(SourcePath))
  159. {
  160. if (!string.IsNullOrEmpty(dateTimeStr))
  161. {
  162. FileInfo flinfo = new FileInfo(SourcePath);
  163. flinfo.CopyTo(DestinationPath + dateTimeStr + "_" + flinfo.Name, overwriteexisting);
  164. }
  165. else {
  166. FileInfo flinfo = new FileInfo(SourcePath);
  167. flinfo.CopyTo(DestinationPath + "\\" + flinfo.Name, overwriteexisting);
  168. }
  169. }
  170. ret = true;
  171. }
  172. catch (Exception ex)
  173. {
  174. //DeleteFolder(DestinationPath);
  175. ret = false;
  176. }
  177. return ret;
  178. }
  179. /// <summary>
  180. /// 目录下所有内容复制
  181. /// </summary>
  182. /// <param name="SourcePath">要Copy的文件</param>
  183. /// <param name="DestinationPath">要复制到哪个地方(具体文件)</param>
  184. /// <param name="overwriteexisting">是否覆盖</param>
  185. /// <returns></returns>
  186. public static bool CopyFilePath(string SourcePath, string DestinationPath, string dateTimeStr, bool overwriteexisting)
  187. {
  188. bool ret = false;
  189. try
  190. {
  191. SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
  192. DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
  193. if (Directory.Exists(SourcePath))
  194. {
  195. if (Directory.Exists(DestinationPath) == false)
  196. Directory.CreateDirectory(DestinationPath);
  197. foreach (string fls in Directory.GetFiles(SourcePath))
  198. {
  199. FileInfo flinfo = new FileInfo(fls);
  200. flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
  201. }
  202. foreach (string drs in Directory.GetDirectories(SourcePath))
  203. {
  204. DirectoryInfo drinfo = new DirectoryInfo(drs);
  205. if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
  206. ret = false;
  207. }
  208. }
  209. else
  210. {
  211. //复制单个文件用的
  212. SourcePath = SourcePath.EndsWith(@"\") ? SourcePath.Substring(0, SourcePath.Length - 1) : SourcePath;
  213. if (File.Exists(SourcePath))
  214. {
  215. FileInfo flinfo = new FileInfo(SourcePath);
  216. flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
  217. }
  218. }
  219. ret = true;
  220. }
  221. catch (Exception)
  222. {
  223. DeleteFolder(DestinationPath);
  224. ret = false;
  225. }
  226. return ret;
  227. }
  228. /// <summary>
  229. /// 目录下所有内容复制
  230. /// </summary>
  231. /// <param name="SourcePath">要Copy的文件夹</param>
  232. /// <param name="DestinationPath">要复制到哪个地方</param>
  233. /// <param name="overwriteexisting">是否覆盖</param>
  234. /// <returns></returns>
  235. public static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
  236. {
  237. bool ret = false;
  238. try
  239. {
  240. SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
  241. DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";
  242. if (Directory.Exists(SourcePath))
  243. {
  244. if (Directory.Exists(DestinationPath) == false)
  245. Directory.CreateDirectory(DestinationPath);
  246. foreach (string fls in Directory.GetFiles(SourcePath))
  247. {
  248. FileInfo flinfo = new FileInfo(fls);
  249. flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
  250. }
  251. foreach (string drs in Directory.GetDirectories(SourcePath))
  252. {
  253. DirectoryInfo drinfo = new DirectoryInfo(drs);
  254. if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
  255. ret = false;
  256. }
  257. }
  258. else
  259. {
  260. //复制单个文件用的
  261. SourcePath = SourcePath.EndsWith(@"\") ? SourcePath.Substring(0, SourcePath.Length - 1) : SourcePath;
  262. if (File.Exists(SourcePath))
  263. {
  264. FileInfo flinfo = new FileInfo(SourcePath);
  265. flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
  266. }
  267. }
  268. ret = true;
  269. }
  270. catch (Exception)
  271. {
  272. DeleteFolder(DestinationPath);
  273. ret = false;
  274. }
  275. return ret;
  276. }
  277. /// <summary>
  278. /// 删除目录及内部所有文件
  279. /// </summary>
  280. /// <param name="dir">要删除的目录</param>
  281. public static void DeleteFolder(string dir)
  282. {
  283. try
  284. {
  285. if (System.IO.Directory.Exists(dir))
  286. {
  287. string[] fileSystemEntries = System.IO.Directory.GetFileSystemEntries(dir);
  288. for (int i = 0; i < fileSystemEntries.Length; i++)
  289. {
  290. string text = fileSystemEntries[i];
  291. if (System.IO.File.Exists(text))
  292. {
  293. System.IO.File.Delete(text);
  294. }
  295. else
  296. {
  297. DeleteFolder(text);
  298. }
  299. }
  300. System.IO.Directory.Delete(dir);
  301. }
  302. }
  303. catch (Exception)
  304. {
  305. }
  306. }
  307. /// <summary>
  308. /// 判断指定文件夹及子文件夹内是否有文件正被打开
  309. /// 1.文件夹内有文件被打开 0.没有 -1.文件夹不存在
  310. /// </summary>
  311. /// <param name="path"></param>
  312. /// <returns></returns>
  313. public static int IsFileOpened(string dir)
  314. {
  315. if (System.IO.Directory.Exists(dir))
  316. {
  317. string[] fileSystemEntries = System.IO.Directory.GetFileSystemEntries(dir);
  318. for (int i = 0; i < fileSystemEntries.Length; i++)
  319. {
  320. string text = fileSystemEntries[i];
  321. if (System.IO.File.Exists(text))
  322. {
  323. try
  324. {
  325. System.IO.File.Move(text, text);
  326. }
  327. catch (Exception)
  328. {
  329. return 1;
  330. }
  331. }
  332. else
  333. {
  334. //递归时外层要先接收内层的结果,无法直接多层catch出去
  335. if (IsFileOpened(text) == 1)
  336. return 1;
  337. }
  338. }
  339. return 0;
  340. }
  341. return -1;
  342. }
  343. /// <summary>
  344. /// 计算文件的大小
  345. /// </summary>
  346. /// <param name="lengthOfDocument"></param>
  347. /// <returns></returns>
  348. public static string GetLength(long lengthOfDocument)
  349. {
  350. if (lengthOfDocument < 1024)
  351. return string.Format(lengthOfDocument.ToString() + 'B');
  352. else if (lengthOfDocument > 1024 && lengthOfDocument <= Math.Pow(1024, 2))
  353. return string.Format(Math.Floor(lengthOfDocument / 1024.0).ToString() + "KB");
  354. else if (lengthOfDocument > Math.Pow(1024, 2) && lengthOfDocument <= Math.Pow(1024, 3))
  355. return string.Format(Math.Round(lengthOfDocument / 1024.0 / 1024.0, 2).ToString() + "M");
  356. else
  357. return string.Format(Math.Round(lengthOfDocument / 1024.0 / 1024.0 / 1024.0, 2).ToString() + "GB");
  358. }
  359. /// <summary>
  360. /// 判断文件是word还是excel
  361. /// 1.word; 2.excel; 0.其他
  362. /// </summary>
  363. /// <param name="filePath"></param>
  364. /// <returns></returns>
  365. public static int IsFileWordOrExcel(string filePath)
  366. {
  367. if (!string.IsNullOrEmpty(filePath))
  368. {
  369. string fileExtension = Path.GetExtension(filePath);
  370. if (fileExtension == ".docx" || fileExtension == ".doc")
  371. return 1;
  372. else if (fileExtension == ".xls" || fileExtension == ".xlsx")
  373. return 2;
  374. else
  375. return 0;
  376. }
  377. else
  378. return 0;
  379. }
  380. /// <summary>
  381. /// 获取文件的创建时间
  382. /// </summary>
  383. /// <param name="filePath"></param>
  384. /// <returns></returns>
  385. public static string GetFileCreationTime(string filePath)
  386. {
  387. FileInfo fi = new FileInfo(filePath);
  388. if (fi != null)
  389. return fi.LastWriteTime.ToString();//创建时间同一分钟内可能会相同,不清楚机制,暂时调整为修改时间;
  390. else
  391. return "";
  392. }
  393. /// <summary>
  394. /// 判断文件夹内是否有同名文件
  395. /// </summary>
  396. /// <param name="name"></param>
  397. /// <param name="filePath"></param>
  398. /// <returns></returns>
  399. public static bool IsFileNameExist(string name, string filePath)
  400. {
  401. if (System.IO.Directory.Exists(filePath))
  402. {
  403. DirectoryInfo theFolder = new DirectoryInfo(filePath);
  404. FileInfo[] fileList = theFolder.GetFiles();
  405. foreach (FileInfo fileItem in fileList)
  406. {
  407. if (Path.GetFileNameWithoutExtension(fileItem.FullName) == name)
  408. return true;
  409. }
  410. }
  411. return false;
  412. }
  413. public static void RecursionDirector(string dirs, TreeNode node)
  414. {
  415. //绑定到指定的文件夹目录
  416. DirectoryInfo dir = new DirectoryInfo(dirs);
  417. //检索表示当前目录的文件和子目录
  418. FileSystemInfo[] fsinfos = dir.GetFileSystemInfos();
  419. //遍历检索的文件和子目录
  420. foreach (FileSystemInfo fsinfo in fsinfos)
  421. {
  422. //判断是否为空文件夹  
  423. if (fsinfo is DirectoryInfo)
  424. {
  425. TreeNode temp = new TreeNode();
  426. temp.Name = fsinfo.FullName;
  427. temp.Text = fsinfo.FullName;
  428. node.Nodes.Add(temp);
  429. //递归调用
  430. RecursionDirector(fsinfo.FullName, temp);
  431. }
  432. }
  433. }
  434. public static string ReadFileOwner(string path)
  435. {
  436. var fs = System.IO.File.GetAccessControl(path);
  437. var sid = fs.GetOwner(typeof(SecurityIdentifier));
  438. var ntAccount = sid.Translate(typeof(NTAccount));
  439. return ntAccount.ToString();
  440. }
  441. /// <summary>
  442. /// 获取相机sn和名称,如果不存在
  443. /// </summary>
  444. /// <param name="path"></param>
  445. /// <param name="cameraSN"></param>
  446. /// <param name="cameraName"></param>
  447. /// <returns></returns>
  448. public static bool CheckCameraSNAndReturnName(string path, string cameraSN, out string cameraName)
  449. {
  450. cameraName = null;
  451. try
  452. {
  453. byte[] buffer = File.ReadAllBytes(path);
  454. string keys = Encoding.UTF8.GetString(buffer);
  455. var bytes = Convert.FromBase64String(keys);
  456. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  457. rsa.FromXmlString(privateKey);
  458. int encriptedChunckSize = rsa.KeySize / 8;
  459. int dataLength = bytes.Length;
  460. int iterations = dataLength / encriptedChunckSize;
  461. ArrayList arrayList = new ArrayList();
  462. for (int i = 0; i < iterations; i++)
  463. {
  464. byte[] tempBytes = new byte[encriptedChunckSize];
  465. System.Buffer.BlockCopy(bytes,
  466. encriptedChunckSize * i,
  467. tempBytes, 0, tempBytes.Length);
  468. System.Array.Reverse(tempBytes);
  469. arrayList.AddRange(rsa.Decrypt(tempBytes, false));
  470. }
  471. var descrypt = (byte[])arrayList.ToArray(typeof(Byte));
  472. string result = Encoding.UTF8.GetString(descrypt);
  473. if (result != null)
  474. {
  475. string[] arr = result.Split('|');
  476. string v = arr.ToList().Find(a => a.IndexOf(cameraSN, StringComparison.OrdinalIgnoreCase) >= 0);
  477. if (!string.IsNullOrEmpty(v))
  478. {
  479. cameraName = v.Split('-')[0];
  480. return true;
  481. }
  482. }
  483. return false;
  484. }
  485. catch (Exception)
  486. {
  487. }
  488. return false;
  489. }
  490. }
  491. }