FileFuns.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using System;
  2. using System.Collections;
  3. using System.Drawing;
  4. using System.Drawing.Imaging;
  5. using System.IO;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Security.Cryptography;
  9. using System.Security.Permissions;
  10. using System.Text;
  11. namespace CommonTool
  12. {
  13. public class FileFuns
  14. {
  15. /// <summary>
  16. /// 判断文件是否已经打开 Open
  17. /// </summary>
  18. /// <param name="filePath"></param>
  19. /// <returns></returns>
  20. public static bool IsFileOpen(string filePath)
  21. {
  22. if (!File.Exists(filePath))
  23. {
  24. WriteLog.LogError(filePath + "文件都不存在!");
  25. return true;
  26. }
  27. IntPtr vHandle = _lopen(filePath, OfReadwrite | OfShareDenyNone);
  28. if (vHandle == HfileError)
  29. {
  30. WriteLog.LogError(filePath + "文件被占用!");
  31. return true;
  32. }
  33. CloseHandle(vHandle);
  34. WriteLog.LogInfo(filePath + "没有被占用!");
  35. return false;
  36. }
  37. public static void DeleteFile(string filePath)
  38. {
  39. File.Delete(filePath);
  40. }
  41. /// <summary>
  42. /// 文件正在被使用
  43. /// </summary>
  44. /// <param name="fileName"></param>
  45. /// <returns></returns>
  46. public static bool IsFileInUse(string fileName)
  47. {
  48. bool inUse;
  49. FileStream fs = null;
  50. try
  51. {
  52. fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
  53. inUse = false;
  54. }
  55. catch
  56. {
  57. inUse = true;
  58. }
  59. finally
  60. {
  61. fs?.Close();
  62. }
  63. return inUse;//true表示正在使用,false没有使用
  64. }
  65. // Methods
  66. public static void AddSeachingFolder(string pcSeachingFolder)
  67. {
  68. pcSeachingFolder = GetFolder(pcSeachingFolder, false);
  69. if (pcSeachingFolder != "" && !SeachingFolders.Contains(pcSeachingFolder))
  70. {
  71. SeachingFolders.Add(pcSeachingFolder);
  72. }
  73. }
  74. private static bool DemainSecurity()
  75. {
  76. bool flag1 = true;
  77. try
  78. {
  79. new PrincipalPermission("qwertyuiopasdfgh", "qwertyuiopasdfgh").Demand();
  80. }
  81. catch (Exception)
  82. {
  83. flag1 = false;
  84. }
  85. return flag1;
  86. }
  87. public static bool FileExists(string pcFileName)
  88. {
  89. string text1 = GetFullPathFileName(pcFileName);
  90. return (text1 != "");
  91. }
  92. public static string GetAssemblyFolder()
  93. {
  94. // ReSharper disable once AssignNullToNotNullAttribute
  95. FileInfo info1 = new FileInfo(Assembly.GetCallingAssembly().Location);
  96. return info1.DirectoryName;
  97. }
  98. public static string GetFolder(string pcFolder, bool plCreateFolder)
  99. {
  100. string text1 = pcFolder;
  101. text1 = text1.TrimEnd('\\') + @"\";
  102. if (Directory.Exists(text1))
  103. {
  104. return text1;
  105. }
  106. if (plCreateFolder)
  107. {
  108. try
  109. {
  110. Directory.CreateDirectory(text1);
  111. }
  112. catch (Exception)
  113. {
  114. text1 = "";
  115. }
  116. return text1;
  117. }
  118. return "";
  119. }
  120. public static string GetFullPathFileName(string pcFileName)
  121. {
  122. string text1 = "";
  123. if (File.Exists(pcFileName))
  124. {
  125. text1 = pcFileName;
  126. }
  127. else
  128. {
  129. foreach (string text2 in SeachingFolders)
  130. {
  131. string text3 = text2 + pcFileName;
  132. if (File.Exists(text3))
  133. {
  134. text1 = text3;
  135. break;
  136. }
  137. }
  138. }
  139. if (text1 != "")
  140. {
  141. FileInfo info1 = new FileInfo(text1);
  142. text1 = info1.FullName;
  143. }
  144. return text1;
  145. }
  146. private static bool Open(string pcFileName)
  147. {
  148. bool flag1 = false;
  149. if (DemainSecurity())
  150. {
  151. flag1 = Open(pcFileName, _key);
  152. }
  153. return flag1;
  154. }
  155. private static bool Open(string pcFileName, string pcSecurityCode)
  156. {
  157. //bool flag1 = false;
  158. Close();
  159. string text1 = GetFullPathFileName(pcFileName);
  160. if ((pcSecurityCode != "qwertyuiopasdfgh") || (text1 == ""))
  161. {
  162. return false;
  163. }
  164. byte[] buffer1 = Encoding.ASCII.GetBytes(_key);
  165. byte[] buffer2 = Encoding.ASCII.GetBytes(_IV);
  166. FileStream stream1 = new FileStream(text1, FileMode.Open, FileAccess.Read);
  167. SymmetricAlgorithm algorithm1 = SymmetricAlgorithm.Create();
  168. CryptoStream stream2 = new CryptoStream(stream1, algorithm1.CreateDecryptor(buffer1, buffer2), CryptoStreamMode.Read);
  169. MemoryStream stream3 = new MemoryStream();
  170. byte[] buffer3 = new byte[0x1388];
  171. int num1 = 0x1388;
  172. while (num1 == 0x1388)
  173. {
  174. num1 = stream2.Read(buffer3, 0, 0x1388);
  175. if (num1 > 0)
  176. {
  177. stream3.Write(buffer3, 0, num1);
  178. }
  179. }
  180. stream1.Close();
  181. stream2.Close();
  182. _reader = new StreamReader(stream3);
  183. return true;
  184. }
  185. public static string ReadAll()
  186. {
  187. string text1 = "";
  188. if (_reader != null)
  189. {
  190. ((MemoryStream)_reader.BaseStream).Seek(offset: 0, loc: SeekOrigin.Begin);
  191. text1 = _reader.ReadToEnd();
  192. }
  193. return text1;
  194. }
  195. public static string ReadAll(string pcFileName)
  196. {
  197. string text1 = "";
  198. if (Open(pcFileName))
  199. {
  200. text1 = ReadAll();
  201. }
  202. return text1;
  203. }
  204. public static string ReadEncryptedFile(string pcFileName)
  205. {
  206. return ReadEncryptedFile(pcFileName, _IV);
  207. }
  208. public static string ReadEncryptedFile(string pcFileName, string pcSecurityCode)
  209. {
  210. string text1 = "";
  211. string text2 = GetFullPathFileName(pcFileName);
  212. if (text2 != "")
  213. {
  214. byte[] buffer1 = Encoding.ASCII.GetBytes(pcSecurityCode);
  215. byte[] buffer2 = Encoding.ASCII.GetBytes(pcSecurityCode);
  216. FileStream stream1 = new FileStream(text2, FileMode.Open, FileAccess.Read);
  217. SymmetricAlgorithm algorithm1 = SymmetricAlgorithm.Create();
  218. CryptoStream stream2 = new CryptoStream(stream1, algorithm1.CreateDecryptor(buffer1, buffer2), CryptoStreamMode.Read);
  219. MemoryStream stream3 = new MemoryStream();
  220. byte[] buffer3 = new byte[0x1388];
  221. int num1 = 0x1388;
  222. while (num1 == 0x1388)
  223. {
  224. num1 = stream2.Read(buffer3, 0, 0x1388);
  225. if (num1 > 0)
  226. {
  227. stream3.Write(buffer3, 0, num1);
  228. }
  229. }
  230. stream1.Close();
  231. stream2.Close();
  232. StreamReader reader1 = new StreamReader(stream3);
  233. stream3.Seek(0, SeekOrigin.Begin);
  234. text1 = reader1.ReadToEnd();
  235. reader1.Close();
  236. }
  237. return text1;
  238. }
  239. public static string ReadFileAsString(string pcFileName)
  240. {
  241. string text1 = "";
  242. pcFileName = GetFullPathFileName(pcFileName);
  243. if (pcFileName != "")
  244. {
  245. FileStream fs = new FileStream(pcFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  246. StreamReader reader = new StreamReader(fs);
  247. //StreamReader reader = new StreamReader(pcFileName, Encoding.UTF8);
  248. text1 = reader.ReadToEnd();
  249. reader.Close();
  250. }
  251. return text1;
  252. }
  253. public static string ReadSection(string pcSectionName)
  254. {
  255. string text1 = "";
  256. if (_reader != null)
  257. {
  258. string text2 = ReadAll();
  259. pcSectionName = "[" + pcSectionName + "]";
  260. int num1 = text2.ToUpper().IndexOf(pcSectionName.ToUpper(), StringComparison.Ordinal);
  261. if (num1 >= 0)
  262. {
  263. num1 = text2.IndexOf("\r\n", num1, StringComparison.Ordinal);
  264. }
  265. if (num1 < 0)
  266. {
  267. return text1;
  268. }
  269. num1 += 2;
  270. _reader.BaseStream.Seek(num1, SeekOrigin.Begin);
  271. for (string text4 = _reader.ReadLine(); text4 != null; text4 = _reader.ReadLine())
  272. {
  273. if (((text4 != "") && (text4[0] == '[')) && (text4[text4.Length - 1] == ']'))
  274. {
  275. return text1;
  276. }
  277. text1 = text1 + ((text1 == "") ? "" : "\r\n") + text4;
  278. }
  279. }
  280. return text1;
  281. }
  282. public static string ReadSection(string pcSectionName, string pcFileName)
  283. {
  284. string text1 = "";
  285. if (Open(pcFileName))
  286. {
  287. text1 = ReadSection(pcSectionName);
  288. }
  289. return text1;
  290. }
  291. private static string ReadSection(string pcSectionName, string pcFileName, string pcSecurityCode)
  292. {
  293. string text1 = "";
  294. if (Open(pcFileName, pcSecurityCode))
  295. {
  296. text1 = ReadSection(pcSectionName);
  297. }
  298. return text1;
  299. }
  300. public static void SaveConnectionString(string pcConnStr)
  301. {
  302. if (pcConnStr != null && pcConnStr.Trim().Length > 0)
  303. {
  304. string lcFullName = GetFullPathFileName("RSDB.cfg");
  305. SaveToFile(pcConnStr, lcFullName);
  306. }
  307. }
  308. public static string ReadSystemLicense()
  309. {
  310. return ReadSection("MachineId", "License", "qwertyuiopasdfgh");
  311. }
  312. public static void RemoveSeachingFolder(string pcSeachingFolder)
  313. {
  314. if (SeachingFolders.Contains(pcSeachingFolder))
  315. {
  316. SeachingFolders.Remove(pcSeachingFolder);
  317. }
  318. }
  319. /// <summary>
  320. /// 将图片保存到指定的文件中
  321. /// </summary>
  322. /// <param name="pcFileName"></param>
  323. /// <param name="poImage"></param>
  324. /// <returns></returns>
  325. public static bool SaveImageToFile(string pcFileName, Image poImage)
  326. {
  327. bool flag1 = false;
  328. if (pcFileName == "")
  329. {
  330. return false;
  331. }
  332. ImageFormat format1 = ImageFormat.Bmp;
  333. FileInfo info1 = new FileInfo(pcFileName);
  334. switch (info1.Extension.ToUpper().Trim())
  335. {
  336. case "BMP":
  337. format1 = ImageFormat.Bmp;
  338. goto Label_0091;
  339. case "WMF":
  340. format1 = ImageFormat.Wmf;
  341. break;
  342. case "JPG":
  343. format1 = ImageFormat.Jpeg;
  344. break;
  345. }
  346. Label_0091:
  347. try
  348. {
  349. poImage.Save(pcFileName, format1);
  350. flag1 = true;
  351. }
  352. catch (Exception)
  353. {
  354. // ignored
  355. }
  356. return flag1;
  357. }
  358. /// <summary>
  359. /// 将字符串加密保存到指定的文件中
  360. /// </summary>
  361. /// <param name="pcStringToSave"></param>
  362. /// <param name="pcFileName"></param>
  363. public static void SaveToFile(string pcStringToSave, string pcFileName)
  364. {
  365. FileStream stream1 = new FileStream(pcFileName, FileMode.OpenOrCreate, FileAccess.Write);
  366. stream1.SetLength(0);
  367. byte[] buffer1 = Encoding.ASCII.GetBytes(_key);
  368. byte[] buffer2 = Encoding.ASCII.GetBytes(_IV);
  369. SymmetricAlgorithm algorithm1 = SymmetricAlgorithm.Create();
  370. CryptoStream stream2 = new CryptoStream(stream1, algorithm1.CreateEncryptor(buffer1, buffer2), CryptoStreamMode.Write);
  371. byte[] buffer3 = Encoding.ASCII.GetBytes(pcStringToSave);
  372. stream2.Write(buffer3, 0, buffer3.Length);
  373. stream1.Flush();
  374. stream2.Close();
  375. stream1.Close();
  376. }
  377. //private static string TranslateFileFilter(string pcFileType)
  378. //{
  379. // string text2;
  380. // string text1 = "All Files (*.*)|*.*";
  381. // if ((text2 = pcFileType.ToUpper()) == null)
  382. // {
  383. // return text1;
  384. // }
  385. // text2 = string.IsInterned(text2);
  386. // if (text2 == "DLL")
  387. // {
  388. // return "Library files (*.dll)|*.dll";
  389. // }
  390. // if (text2 == "RSC")
  391. // {
  392. // return "Configuration files (*.rsc)|*.rsc";
  393. // }
  394. // if (text2 == "XLS")
  395. // {
  396. // return "Excel Files (*.xls)|*.xls";
  397. // }
  398. // if (text2 != "IMAGE")
  399. // {
  400. // return text1;
  401. // }
  402. // return "Bitmap files (*.bmp)|*.bmp|JPG Files (*.jpg)|*.jpg|WMF Files (*.wmf)|*.wmf|All Files (*.*)|*.*";
  403. //}
  404. /// <summary>
  405. /// 将字符串内容写入到文件中
  406. /// </summary>
  407. /// <param name="pcStringToWrite">需要写入的字符串内容</param>
  408. /// <param name="pcFileName">文件名称</param>
  409. /// <returns></returns>
  410. public static bool WriteStringToFile(string pcStringToWrite, string pcFileName)
  411. {
  412. //bool flag1 = true;
  413. if (File.Exists(pcFileName))
  414. {
  415. File.Delete(pcFileName);
  416. }
  417. StreamWriter writer1 = new StreamWriter(pcFileName, false, Encoding.UTF8);
  418. writer1.Write(pcStringToWrite);
  419. writer1.Flush();
  420. writer1.Close();
  421. return true;
  422. }
  423. /// <summary>
  424. /// 得到文件里的内容
  425. /// </summary>
  426. /// <param name="filePath">文件</param>
  427. /// <returns>文件内容</returns>
  428. public static string GetStream(string filePath)
  429. {
  430. FileStream stream1 = new FileStream(filePath, FileMode.Open);
  431. byte[] buffer1 = new byte[Convert.ToInt32(stream1.Length)];
  432. stream1.Read(buffer1, 0, buffer1.Length);
  433. stream1.Close();
  434. return Convert.ToBase64String(buffer1);
  435. }
  436. // Properties
  437. public static ArrayList SeachingFolders => _seachingFolders ?? (_seachingFolders = new ArrayList());
  438. public static void Close()
  439. {
  440. _reader?.Close();
  441. _reader = null;
  442. }
  443. // Fields
  444. [DllImport("kernel32.dll")]
  445. public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
  446. [DllImport("kernel32.dll")]
  447. public static extern bool CloseHandle(IntPtr hObject);
  448. const int OfReadwrite = 2;
  449. const int OfShareDenyNone = 0x40;
  450. //const int Buffersize = 0x1388;
  451. static readonly IntPtr HfileError = new IntPtr(-1);
  452. static readonly string _IV = "qwertyuiopasdfgh";
  453. static readonly string _key = "qwertyuiopasdfgh";
  454. static StreamReader _reader;
  455. static ArrayList _seachingFolders = new ArrayList();
  456. #region 直接删除指定目录下的所有文件及文件夹(保留目录)
  457. /// <summary>
  458. ///直接删除指定目录下的所有文件及文件夹(保留目录)
  459. /// </summary>
  460. /// <param name="strPath">文件夹路径</param>
  461. /// <returns>执行结果</returns>
  462. public static bool DeleteDir(string strPath)
  463. {
  464. try
  465. {
  466. strPath = @strPath.Trim().ToString();// 清除空格
  467. if (System.IO.Directory.Exists(strPath))// 判断文件夹是否存在
  468. {
  469. string[] strDirs = System.IO.Directory.GetDirectories(strPath);// 获得文件夹数组
  470. string[] strFiles = System.IO.Directory.GetFiles(strPath);// 获得文件数组
  471. foreach (string strFile in strFiles)// 遍历所有子文件夹
  472. {
  473. //System.Diagnostics.Debug.Write(strFile + "-deleted");
  474. System.IO.File.Delete(strFile);// 删除文件夹
  475. }
  476. foreach (string strdir in strDirs)// 遍历所有文件
  477. {
  478. //System.Diagnostics.Debug.Write(strdir + "-deleted");
  479. System.IO.Directory.Delete(strdir, true);// 删除文件
  480. }
  481. }
  482. return true;// 成功
  483. }
  484. catch (Exception Exp) // 异常处理
  485. {
  486. System.Diagnostics.Debug.Write(Exp.Message.ToString());// 异常信息
  487. return false;// 失败
  488. }
  489. }
  490. #endregion
  491. }
  492. }