Make_FirstInspect.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. using DevExpress.Utils.OAuth;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http;
  12. using System.Net.Sockets;
  13. using System.Security.Policy;
  14. using System.ServiceModel;
  15. using System.Text;
  16. using System.Text.RegularExpressions;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Windows.Forms;
  20. using UAS_MES_NEW.DataOperate;
  21. using UAS_MES_NEW.Entity;
  22. using UAS_MES_NEW.PublicMethod;
  23. namespace UAS_MES_NEW.Make
  24. {
  25. public partial class Make_FirstInspect : Form
  26. {
  27. public Make_FirstInspect()
  28. {
  29. InitializeComponent();
  30. }
  31. DataHelper dh;
  32. DataTable dt;
  33. FileSystemWatcher watcher;
  34. string currFileType , equiType ;
  35. List<string> fileList = new List<string>();
  36. string workOrder,line,sideType,sn;
  37. private void Make_ParseLog_Load(object sender, EventArgs e)
  38. {
  39. dh = SystemInf.dh;
  40. fileList.Add("D:\\FAIReport");
  41. txtPath.Text = fileList[0];
  42. currFileType = "txt";
  43. equiType = "首件测试仪";
  44. watcher = new FileSystemWatcher();
  45. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  46. watcher.Created += OnFileCreated;
  47. /*watcher.Changed += OnFileChanged;
  48. watcher.Deleted += OnFileChanged;
  49. watcher.Renamed += OnFileChanged;*/
  50. }
  51. private void Choose_Click(object sender, EventArgs e)
  52. {
  53. using (var dialog = new FolderBrowserDialog())
  54. {
  55. if (dialog.ShowDialog() == DialogResult.OK)
  56. {
  57. txtPath.Text = dialog.SelectedPath;
  58. txtPath.Enabled = false;
  59. watcher.EnableRaisingEvents = false;
  60. }
  61. }
  62. }
  63. private void claerBtn_Click(object sender, EventArgs e)
  64. {
  65. lstFiles.Items.Clear();
  66. }
  67. private async void allParse_Click(object sender, EventArgs e)
  68. {
  69. if (String.IsNullOrEmpty(txtPath.Text))
  70. {
  71. txtPath.Focus();
  72. txtPath.SelectAll();
  73. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  74. return;
  75. }
  76. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  77. if (txtFiles.Length == 0)
  78. {
  79. LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  80. return;
  81. }
  82. txtPath.Enabled = false;
  83. Choose.Enabled = false;
  84. generateRadio.Enabled = false;
  85. try
  86. {
  87. await Task.Run(() => RefreshFileList());
  88. }
  89. catch (Exception ex)
  90. {
  91. LogMessage(0, $"处理失败: {ex.Message}");
  92. }
  93. finally
  94. {
  95. txtPath.Enabled = true;
  96. Choose.Enabled = true;
  97. generateRadio.Enabled = true;
  98. }
  99. }
  100. private void onWatch_Click(object sender, EventArgs e)
  101. {
  102. if (String.IsNullOrEmpty(txtPath.Text))
  103. {
  104. txtPath.Focus();
  105. txtPath.SelectAll();
  106. MessageBox.Show(this.ParentForm, "请选择监控路径", "提示");
  107. return;
  108. }
  109. try
  110. {
  111. watcher.Path = txtPath.Text;
  112. watcher.Filter = $"*.{currFileType}";
  113. if (onWatch.Text == "开启监控")
  114. {
  115. onWatch.Text = "关闭监控";
  116. txtPath.Enabled = false;
  117. Choose.Enabled = false;
  118. generateRadio.Enabled = false;
  119. watcher.EnableRaisingEvents = true;
  120. }
  121. else
  122. {
  123. onWatch.Text = "开启监控";
  124. txtPath.Enabled = true;
  125. Choose.Enabled = true;
  126. generateRadio.Enabled = true;
  127. watcher.EnableRaisingEvents = false;
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  133. }
  134. }
  135. private async void OnFileCreated(object sender, FileSystemEventArgs e)
  136. {
  137. try
  138. {
  139. await Task.Delay(500);
  140. await Task.Run(() => RefreshFileList());
  141. }
  142. catch (Exception ex)
  143. {
  144. LogMessage(0, $"监控文件处理失败: {ex.Message}");
  145. }
  146. }
  147. private async void OnFileChanged(object sender, FileSystemEventArgs e)
  148. {
  149. if (e.ChangeType == WatcherChangeTypes.Changed)
  150. {
  151. try
  152. {
  153. await Task.Delay(500);
  154. await Task.Run(() => RefreshFileList());
  155. }
  156. catch (Exception ex)
  157. {
  158. LogMessage(0, $"监控文件变更处理失败: {ex.Message}");
  159. }
  160. }
  161. }
  162. private async Task RefreshFileList()
  163. {
  164. if (lstFiles.InvokeRequired)
  165. {
  166. await Task.Run(() =>
  167. {
  168. lstFiles.Invoke(new Action(async () => await RefreshFileList()));
  169. });
  170. return;
  171. }
  172. try
  173. {
  174. if (!Directory.Exists(txtPath.Text))
  175. {
  176. LogMessage(0, $"NG,目录不存在: {txtPath.Text}");
  177. return;
  178. }
  179. string[] txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  180. if (txtFiles.Length == 0)
  181. {
  182. return;
  183. }
  184. List<string> itemFileList = new List<string>();
  185. foreach (string file in txtFiles)
  186. {
  187. itemFileList.Clear();
  188. itemFileList.Add(file);
  189. byte[] bytes = File.ReadAllBytes(file);
  190. Encoding encoding = Encoding.GetEncoding("GB2312");
  191. string[] lines = File.ReadAllLines(file, encoding);
  192. foreach (string rowLine in lines)
  193. {
  194. if (rowLine.Contains("工单号"))
  195. {
  196. workOrder = rowLine.Replace("工单号:", "");
  197. }
  198. if (rowLine.Contains("生产线"))
  199. {
  200. line = rowLine.Replace("生产线:", "") ;
  201. }
  202. if (rowLine.Contains("样品条码"))
  203. {
  204. sn = rowLine.Replace("样品条码:", "");
  205. }
  206. if (rowLine.Contains("板面"))
  207. {
  208. sideType = rowLine.Replace("板面:", "");
  209. }
  210. }
  211. string pdFile = Regex.Replace(file, ".{7}$", $"{sideType}.pdf");
  212. itemFileList.Add(pdFile);
  213. await InsertDb(itemFileList, workOrder, line, sn);
  214. }
  215. }
  216. catch (Exception ex)
  217. {
  218. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  219. }
  220. }
  221. private async Task InsertDb(List<string> itemFileList, string workOrder, string line, string sn)
  222. {
  223. try
  224. {
  225. var checkTasks = itemFileList.Select(async filePath =>
  226. {
  227. if (!File.Exists(filePath))
  228. {
  229. return $"NG,{Path.GetFileName(filePath)}日志文件不存在: {filePath}";
  230. }
  231. var content = File.ReadAllText(filePath);
  232. if (content.Length == 0)
  233. {
  234. return $"NG,日志文件中内容为空: {filePath}";
  235. }
  236. string outFileMsg = CheckFileAccess(filePath);
  237. if (outFileMsg != "OK")
  238. {
  239. return outFileMsg + ",请稍后再试";
  240. }
  241. return "OK";
  242. });
  243. var checkRes = await Task.WhenAll(checkTasks);
  244. foreach (var checkItem in checkRes)
  245. {
  246. if (checkItem != "OK")
  247. {
  248. LogMessage(0, checkItem);
  249. return;
  250. }
  251. }
  252. string isCheck = dh.getFieldDataByCondition("make", "nvl(ma_firstitemcheck, 0)", $"ma_code = '{workOrder}'").ToString();
  253. if (string.IsNullOrEmpty(isCheck))
  254. {
  255. LogMessage(0, $"NG,工单号:{workOrder}不存在,请检查报告中{currFileType}文件");
  256. return;
  257. }
  258. string sr_code = dh.getFieldDataByCondition("spotcheckrecord", "sr_code",$"sr_type = '首件检验' AND sr_linecode = '{line}' AND sr_makecode = '{workOrder}'").ToString();
  259. if (string.IsNullOrEmpty(sr_code))
  260. {
  261. if (generateRadio.Checked && isCheck == "-1")
  262. {
  263. string v_macraftcode = dh.getFieldDataByCondition("make", "ma_craftcode", $"ma_code = '{workOrder}'").ToString();
  264. string v_maprodcode = dh.getFieldDataByCondition("make", "ma_prodcode", $"ma_code = '{workOrder}'").ToString();
  265. string em_name = dh.getFieldDataByCondition("craft,make", "cr_qcemp", $"ma_code = '{workOrder}' and cr_prodcode = ma_prodcode and ma_craftcode = cr_code").ToString();
  266. dh.ExecuteSql($@"INSERT INTO spotcheckrecord( sr_id, sr_code, sr_linecode, sr_craftcode, sr_indate,
  267. sr_inman, sr_status, sr_statuscode, sr_makecode, sr_prodcode, sr_source,
  268. sr_contractcode, sr_exportplace, sr_type)
  269. VALUES ( spotcheckrecord_seq.NEXTVAL, 'C' || '{workOrder}', '{line}', '{v_macraftcode}', sysdate,
  270. '{em_name}', '在录入', 'ENTERING', '{workOrder}', '{v_maprodcode}', '工单' || '{workOrder}' || 'SN投入系统自动生成',
  271. '', '{sn}', '首件检验' )", "insert");
  272. }
  273. else
  274. {
  275. if (isCheck == "-1")
  276. {
  277. LogMessage(1, $"报告{itemFileList[1].Replace(txtPath.Text, "")},工单{workOrder}需检查首件,请检查是否需要生成首件任务单");
  278. return;
  279. }
  280. else
  281. {
  282. LogMessage(1, $"报告{itemFileList[1].Replace(txtPath.Text, "")},工单{workOrder}无需检查首件,请核对工单是否检查首件");
  283. return;
  284. }
  285. }
  286. }
  287. //string sr_id = dh.getFieldDataByCondition("spotcheckrecord", "sr_id", $"sr_makecode = '{workOrder}' and sr_linecode = '{line}' and sr_type='首件检验'").ToString();
  288. dt = (DataTable)dh.ExecuteSql($@"SELECT * FROM( SELECT * FROM spotcheckrecord WHERE sr_makecode = '{workOrder}' AND sr_linecode = '{line}'
  289. AND sr_type = '首件检验' ORDER BY sr_indate DESC) WHERE ROWNUM = 1", "select");
  290. string sr_id = dt.Rows[0]["sr_id"].ToString();
  291. string uploadFileApi = "http://192.168.41.232:8098/mes/MEScommon/uploadFiles.action?_noc=1";
  292. Dictionary<string, object> uploadFileParams = new Dictionary<string, object>()
  293. {
  294. {"em_name", "管理员" },
  295. {"em_code", "ADMIN" },
  296. {"caller", "FirstInspect" }
  297. };
  298. string fp_id = await HttpHelper.UploadFilesToRemoteUrl(uploadFileApi, itemFileList[1], uploadFileParams);
  299. if (!string.IsNullOrEmpty(fp_id))
  300. {
  301. LogMessage(1, $"文件上传成功{itemFileList[1].Replace(txtPath.Text, "")}");
  302. dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = CASE WHEN sr_prodtype IS NULL THEN '{fp_id}'
  303. ELSE sr_prodtype || ';{fp_id}' WHERE sr_id = '{sr_id}'", "update");
  304. LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
  305. using (StreamReader SR = new StreamReader(itemFileList[0], Encoding.GetEncoding("GBK")))
  306. {
  307. string Content = SR.ReadToEnd();
  308. SR.Close();
  309. SR.Dispose();
  310. ConsoleLog(Content, itemFileList[0], $"C{workOrder.ToUpper()}");
  311. }
  312. using (StreamReader SR = new StreamReader(itemFileList[1], Encoding.GetEncoding("GBK")))
  313. {
  314. string Content = SR.ReadToEnd();
  315. SR.Close();
  316. SR.Dispose();
  317. ConsoleLog(Content, itemFileList[1], $"C{workOrder.ToUpper()}");
  318. }
  319. }
  320. }
  321. catch (Exception ex)
  322. {
  323. LogMessage(0, $"Error,处理解析异常: {ex.Message}");
  324. }
  325. }
  326. public class HttpHelper
  327. {
  328. public static async Task<string> UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  329. {
  330. try
  331. {
  332. ServicePointManager.DefaultConnectionLimit = 50;
  333. string boundary = DateTime.Now.Ticks.ToString("x");
  334. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  335. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  336. request.Method = "POST";
  337. request.Timeout = 10 * 10000;
  338. request.ContentType = "multipart/form-data; boundary=" + boundary;
  339. Stream rs = request.GetRequestStream();
  340. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  341. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  342. if (dic != null)
  343. {
  344. foreach (string key in dic.Keys)
  345. {
  346. rs.Write(boundarybytes, 0, boundarybytes.Length);
  347. string formitem = string.Format(formdataTemplate, key, dic[key]);
  348. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  349. rs.Write(formitembytes, 0, formitembytes.Length);
  350. }
  351. }
  352. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  353. {
  354. rs.Write(boundarybytes, 0, boundarybytes.Length);
  355. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  356. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  357. rs.Write(headerbytes, 0, headerbytes.Length);
  358. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  359. {
  360. var buffer = new byte[1024];
  361. var bytesRead = 0;
  362. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  363. {
  364. rs.Write(buffer, 0, bytesRead);
  365. }
  366. }
  367. var cr = Encoding.UTF8.GetBytes("\r\n");
  368. rs.Write(cr, 0, cr.Length);
  369. }
  370. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  371. var response = request.GetResponse() as HttpWebResponse;
  372. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  373. string Content = newReader.ReadToEnd();
  374. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  375. List<Dictionary<string, object>> dic2 = null;
  376. dic1 = BaseUtil.ToDictionary(Content);
  377. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  378. string fp_id = "";
  379. if (dic2[0]["filepath"] != null)
  380. {
  381. fp_id = dic2[0]["filepath"].ToString();
  382. }
  383. if (response.StatusCode == HttpStatusCode.OK)
  384. {
  385. return fp_id;
  386. }
  387. }
  388. catch (Exception e)
  389. {
  390. LogicHandler.DoCommandLog("FirstInspect", User.UserCode, "", "", User.UserSourceCode, "上传首件报告", "上传失败", "", "");
  391. Console.WriteLine(e.Message + e.StackTrace);
  392. }
  393. return "";
  394. }
  395. public static async Task<string> PostMultipartAsync(string url, Dictionary<string, string> parameters, string cookie = null)
  396. {
  397. try
  398. {
  399. var handler = new HttpClientHandler();
  400. handler.UseCookies = true;
  401. handler.CookieContainer = new CookieContainer();
  402. if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID="))
  403. {
  404. int start = cookie.IndexOf("JSESSIONID=") + 11;
  405. int end = cookie.IndexOf(";", start);
  406. if (end == -1) end = cookie.Length;
  407. string jsessionId = cookie.Substring(start, end - start).Trim();
  408. handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId));
  409. }
  410. using (var httpClient = new HttpClient(handler))
  411. {
  412. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0");
  413. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
  414. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
  415. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
  416. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Connection", "keep-alive");
  417. string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
  418. using (var memoryStream = new MemoryStream())
  419. {
  420. var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
  421. foreach (var param in parameters)
  422. {
  423. await writer.WriteAsync($"--{boundary}\r\n");
  424. await writer.WriteAsync($"Content-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n");
  425. await writer.WriteAsync($"{param.Value}\r\n");
  426. }
  427. await writer.WriteAsync($"--{boundary}--\r\n");
  428. await writer.FlushAsync();
  429. var content = new ByteArrayContent(memoryStream.ToArray());
  430. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
  431. content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary));
  432. var response = await httpClient.PostAsync(url, content);
  433. string responseBody = await response.Content.ReadAsStringAsync();
  434. return responseBody;
  435. }
  436. }
  437. }
  438. catch (Exception ex)
  439. {
  440. throw new Exception($"HTTP请求失败: {ex.Message}");
  441. }
  442. }
  443. public static async Task<string> PostMultipartWithFileAsync(string url, Dictionary<string, string> parameters, string filePath, string cookie = null)
  444. {
  445. try
  446. {
  447. var handler = new HttpClientHandler();
  448. handler.UseCookies = true;
  449. handler.CookieContainer = new CookieContainer();
  450. if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID="))
  451. {
  452. int start = cookie.IndexOf("JSESSIONID=") + 11;
  453. int end = cookie.IndexOf(";", start);
  454. if (end == -1) end = cookie.Length;
  455. string jsessionId = cookie.Substring(start, end - start).Trim();
  456. handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId));
  457. }
  458. using (var httpClient = new HttpClient(handler))
  459. {
  460. httpClient.DefaultRequestHeaders.ConnectionClose = true;
  461. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0");
  462. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
  463. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
  464. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
  465. string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
  466. string fileName = Path.GetFileName(filePath);
  467. byte[] fileBytes = File.ReadAllBytes(filePath);
  468. using (var memoryStream = new MemoryStream())
  469. {
  470. var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
  471. await writer.WriteAsync($"--{boundary}\r\n");
  472. await writer.WriteAsync($"Content-Disposition: form-data; name=\"em_code\"\r\n\r\n");
  473. await writer.WriteAsync($"{parameters["em_code"]}\r\n");
  474. await writer.WriteAsync($"--{boundary}\r\n");
  475. await writer.WriteAsync($"Content-Disposition: form-data; name=\"caller\"\r\n\r\n");
  476. await writer.WriteAsync($"{parameters["caller"]}\r\n");
  477. await writer.WriteAsync($"--{boundary}\r\n");
  478. await writer.WriteAsync($"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"\r\n");
  479. await writer.WriteAsync($"Content-Type: application/octet-stream\r\n\r\n");
  480. await writer.FlushAsync();
  481. await memoryStream.WriteAsync(fileBytes, 0, fileBytes.Length);
  482. await memoryStream.FlushAsync();
  483. writer.WriteLine();
  484. await writer.WriteAsync($"--{boundary}--\r\n");
  485. await writer.FlushAsync();
  486. var content = new ByteArrayContent(memoryStream.ToArray());
  487. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
  488. content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary));
  489. var response = await httpClient.PostAsync(url, content);
  490. string responseBody = await response.Content.ReadAsStringAsync();
  491. return responseBody;
  492. }
  493. }
  494. }
  495. catch (Exception ex)
  496. {
  497. throw new Exception($"HTTP请求失败: {ex.Message}");
  498. }
  499. }
  500. }
  501. public string CheckFileAccess(string filePath)
  502. {
  503. try
  504. {
  505. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  506. {
  507. return "OK";
  508. }
  509. }
  510. catch (IOException ex)
  511. {
  512. return "NG,文件被占用: " + ex.Message;
  513. }
  514. catch (UnauthorizedAccessException ex)
  515. {
  516. return "NG,权限不足,无法访问文件: " + ex.Message;
  517. }
  518. catch (Exception ex)
  519. {
  520. return "NG," + ex.Message;
  521. }
  522. }
  523. private bool ConsoleLog(string Content, string PathName, string SN)
  524. {
  525. try
  526. {
  527. string sourcePath = Path.GetDirectoryName(PathName);
  528. string newFolderName = "Meslog";
  529. string newFolderPath = Path.Combine(sourcePath, newFolderName, SN);
  530. if (!Directory.Exists(newFolderPath))
  531. {
  532. Directory.CreateDirectory(newFolderPath);
  533. }
  534. string newFileName = Path.GetFileName(PathName);
  535. string newFilePath = Path.Combine(newFolderPath, newFileName);
  536. if (File.Exists(newFilePath))
  537. {
  538. File.Delete(newFilePath);
  539. }
  540. File.Move(PathName, newFilePath);
  541. return true;
  542. }
  543. catch (Exception ex)
  544. {
  545. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  546. return false;
  547. }
  548. }
  549. private void LogMessage(int type, string message)
  550. {
  551. if (type == 0)
  552. {
  553. if (lstFiles.InvokeRequired)
  554. {
  555. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  556. return;
  557. }
  558. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  559. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  560. }
  561. else
  562. {
  563. if (lstOk.InvokeRequired)
  564. {
  565. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  566. return;
  567. }
  568. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  569. lstOk.TopIndex = lstOk.Items.Count - 1;
  570. }
  571. }
  572. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  573. {
  574. if (e.Index < 0) return;
  575. e.DrawBackground();
  576. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  577. Brush color = Brushes.Black;
  578. if (txt.Contains("NG"))
  579. {
  580. color = Brushes.Red;
  581. }
  582. else if (txt.Contains("ERROR"))
  583. {
  584. color = Brushes.Red;
  585. }
  586. else
  587. {
  588. color = Brushes.Green;
  589. }
  590. e.DrawFocusRectangle();
  591. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  592. }
  593. }
  594. }