Make_FirstInspect.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. string uploadFileApi = "http://192.168.41.232:8098/mes/MEScommon/uploadFiles.action?_noc=1";
  289. Dictionary<string, object> uploadFileParams = new Dictionary<string, object>()
  290. {
  291. {"em_name", "管理员" },
  292. {"em_code", "ADMIN" },
  293. {"caller", "FirstInspect" }
  294. };
  295. string fp_id = await HttpHelper.UploadFilesToRemoteUrl(uploadFileApi, itemFileList[1], uploadFileParams);
  296. if (!string.IsNullOrEmpty(fp_id))
  297. {
  298. LogMessage(1, $"文件上传成功{itemFileList[1].Replace(txtPath.Text, "")}");
  299. dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = '{fp_id};' WHERE sr_id = '{sr_id}'", "update");
  300. LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
  301. using (StreamReader SR = new StreamReader(itemFileList[0], Encoding.GetEncoding("GBK")))
  302. {
  303. string Content = SR.ReadToEnd();
  304. SR.Close();
  305. SR.Dispose();
  306. ConsoleLog(Content, itemFileList[0], $"C{workOrder.ToUpper()}");
  307. }
  308. using (StreamReader SR = new StreamReader(itemFileList[1], Encoding.GetEncoding("GBK")))
  309. {
  310. string Content = SR.ReadToEnd();
  311. SR.Close();
  312. SR.Dispose();
  313. ConsoleLog(Content, itemFileList[1], $"C{workOrder.ToUpper()}");
  314. }
  315. }
  316. }
  317. catch (Exception ex)
  318. {
  319. LogMessage(0, $"Error,处理解析异常: {ex.Message}");
  320. }
  321. }
  322. public class HttpHelper
  323. {
  324. public static async Task<string> UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  325. {
  326. try
  327. {
  328. ServicePointManager.DefaultConnectionLimit = 50;
  329. string boundary = DateTime.Now.Ticks.ToString("x");
  330. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  331. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  332. request.Method = "POST";
  333. request.Timeout = 10 * 10000;
  334. request.ContentType = "multipart/form-data; boundary=" + boundary;
  335. Stream rs = request.GetRequestStream();
  336. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  337. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  338. if (dic != null)
  339. {
  340. foreach (string key in dic.Keys)
  341. {
  342. rs.Write(boundarybytes, 0, boundarybytes.Length);
  343. string formitem = string.Format(formdataTemplate, key, dic[key]);
  344. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  345. rs.Write(formitembytes, 0, formitembytes.Length);
  346. }
  347. }
  348. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  349. {
  350. rs.Write(boundarybytes, 0, boundarybytes.Length);
  351. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  352. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  353. rs.Write(headerbytes, 0, headerbytes.Length);
  354. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  355. {
  356. var buffer = new byte[1024];
  357. var bytesRead = 0;
  358. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  359. {
  360. rs.Write(buffer, 0, bytesRead);
  361. }
  362. }
  363. var cr = Encoding.UTF8.GetBytes("\r\n");
  364. rs.Write(cr, 0, cr.Length);
  365. }
  366. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  367. var response = request.GetResponse() as HttpWebResponse;
  368. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  369. string Content = newReader.ReadToEnd();
  370. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  371. List<Dictionary<string, object>> dic2 = null;
  372. dic1 = BaseUtil.ToDictionary(Content);
  373. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  374. string fp_id = "";
  375. if (dic2[0]["filepath"] != null)
  376. {
  377. fp_id = dic2[0]["filepath"].ToString();
  378. }
  379. if (response.StatusCode == HttpStatusCode.OK)
  380. {
  381. return fp_id;
  382. }
  383. }
  384. catch (Exception e)
  385. {
  386. LogicHandler.DoCommandLog("FirstInspect", User.UserCode, "", "", User.UserSourceCode, "上传首件报告", "上传失败", "", "");
  387. Console.WriteLine(e.Message + e.StackTrace);
  388. }
  389. return "";
  390. }
  391. public static async Task<string> PostMultipartAsync(string url, Dictionary<string, string> parameters, string cookie = null)
  392. {
  393. try
  394. {
  395. var handler = new HttpClientHandler();
  396. handler.UseCookies = true;
  397. handler.CookieContainer = new CookieContainer();
  398. if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID="))
  399. {
  400. int start = cookie.IndexOf("JSESSIONID=") + 11;
  401. int end = cookie.IndexOf(";", start);
  402. if (end == -1) end = cookie.Length;
  403. string jsessionId = cookie.Substring(start, end - start).Trim();
  404. handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId));
  405. }
  406. using (var httpClient = new HttpClient(handler))
  407. {
  408. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0");
  409. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
  410. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
  411. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
  412. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Connection", "keep-alive");
  413. string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
  414. using (var memoryStream = new MemoryStream())
  415. {
  416. var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
  417. foreach (var param in parameters)
  418. {
  419. await writer.WriteAsync($"--{boundary}\r\n");
  420. await writer.WriteAsync($"Content-Disposition: form-data; name=\"{param.Key}\"\r\n\r\n");
  421. await writer.WriteAsync($"{param.Value}\r\n");
  422. }
  423. await writer.WriteAsync($"--{boundary}--\r\n");
  424. await writer.FlushAsync();
  425. var content = new ByteArrayContent(memoryStream.ToArray());
  426. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
  427. content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary));
  428. var response = await httpClient.PostAsync(url, content);
  429. string responseBody = await response.Content.ReadAsStringAsync();
  430. return responseBody;
  431. }
  432. }
  433. }
  434. catch (Exception ex)
  435. {
  436. throw new Exception($"HTTP请求失败: {ex.Message}");
  437. }
  438. }
  439. public static async Task<string> PostMultipartWithFileAsync(string url, Dictionary<string, string> parameters, string filePath, string cookie = null)
  440. {
  441. try
  442. {
  443. var handler = new HttpClientHandler();
  444. handler.UseCookies = true;
  445. handler.CookieContainer = new CookieContainer();
  446. if (!string.IsNullOrEmpty(cookie) && cookie.Contains("JSESSIONID="))
  447. {
  448. int start = cookie.IndexOf("JSESSIONID=") + 11;
  449. int end = cookie.IndexOf(";", start);
  450. if (end == -1) end = cookie.Length;
  451. string jsessionId = cookie.Substring(start, end - start).Trim();
  452. handler.CookieContainer.Add(new Uri(url), new Cookie("JSESSIONID", jsessionId));
  453. }
  454. using (var httpClient = new HttpClient(handler))
  455. {
  456. httpClient.DefaultRequestHeaders.ConnectionClose = true;
  457. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "PostmanRuntime/7.29.0");
  458. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
  459. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
  460. httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Cache-Control", "no-cache");
  461. string boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
  462. string fileName = Path.GetFileName(filePath);
  463. byte[] fileBytes = File.ReadAllBytes(filePath);
  464. using (var memoryStream = new MemoryStream())
  465. {
  466. var writer = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
  467. await writer.WriteAsync($"--{boundary}\r\n");
  468. await writer.WriteAsync($"Content-Disposition: form-data; name=\"em_code\"\r\n\r\n");
  469. await writer.WriteAsync($"{parameters["em_code"]}\r\n");
  470. await writer.WriteAsync($"--{boundary}\r\n");
  471. await writer.WriteAsync($"Content-Disposition: form-data; name=\"caller\"\r\n\r\n");
  472. await writer.WriteAsync($"{parameters["caller"]}\r\n");
  473. await writer.WriteAsync($"--{boundary}\r\n");
  474. await writer.WriteAsync($"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"\r\n");
  475. await writer.WriteAsync($"Content-Type: application/octet-stream\r\n\r\n");
  476. await writer.FlushAsync();
  477. await memoryStream.WriteAsync(fileBytes, 0, fileBytes.Length);
  478. await memoryStream.FlushAsync();
  479. writer.WriteLine();
  480. await writer.WriteAsync($"--{boundary}--\r\n");
  481. await writer.FlushAsync();
  482. var content = new ByteArrayContent(memoryStream.ToArray());
  483. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
  484. content.Headers.ContentType.Parameters.Add(new System.Net.Http.Headers.NameValueHeaderValue("boundary", boundary));
  485. var response = await httpClient.PostAsync(url, content);
  486. string responseBody = await response.Content.ReadAsStringAsync();
  487. return responseBody;
  488. }
  489. }
  490. }
  491. catch (Exception ex)
  492. {
  493. throw new Exception($"HTTP请求失败: {ex.Message}");
  494. }
  495. }
  496. }
  497. public string CheckFileAccess(string filePath)
  498. {
  499. try
  500. {
  501. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  502. {
  503. return "OK";
  504. }
  505. }
  506. catch (IOException ex)
  507. {
  508. return "NG,文件被占用: " + ex.Message;
  509. }
  510. catch (UnauthorizedAccessException ex)
  511. {
  512. return "NG,权限不足,无法访问文件: " + ex.Message;
  513. }
  514. catch (Exception ex)
  515. {
  516. return "NG," + ex.Message;
  517. }
  518. }
  519. private bool ConsoleLog(string Content, string PathName, string SN)
  520. {
  521. try
  522. {
  523. string sourcePath = Path.GetDirectoryName(PathName);
  524. string newFolderName = "Meslog";
  525. string newFolderPath = Path.Combine(sourcePath, newFolderName, SN);
  526. if (!Directory.Exists(newFolderPath))
  527. {
  528. Directory.CreateDirectory(newFolderPath);
  529. }
  530. string newFileName = Path.GetFileName(PathName);
  531. string newFilePath = Path.Combine(newFolderPath, newFileName);
  532. if (File.Exists(newFilePath))
  533. {
  534. File.Delete(newFilePath);
  535. }
  536. File.Move(PathName, newFilePath);
  537. return true;
  538. }
  539. catch (Exception ex)
  540. {
  541. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  542. return false;
  543. }
  544. }
  545. private void LogMessage(int type, string message)
  546. {
  547. if (type == 0)
  548. {
  549. if (lstFiles.InvokeRequired)
  550. {
  551. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  552. return;
  553. }
  554. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  555. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  556. }
  557. else
  558. {
  559. if (lstOk.InvokeRequired)
  560. {
  561. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  562. return;
  563. }
  564. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  565. lstOk.TopIndex = lstOk.Items.Count - 1;
  566. }
  567. }
  568. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  569. {
  570. if (e.Index < 0) return;
  571. e.DrawBackground();
  572. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  573. Brush color = Brushes.Black;
  574. if (txt.Contains("NG"))
  575. {
  576. color = Brushes.Red;
  577. }
  578. else if (txt.Contains("ERROR"))
  579. {
  580. color = Brushes.Red;
  581. }
  582. else
  583. {
  584. color = Brushes.Green;
  585. }
  586. e.DrawFocusRectangle();
  587. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  588. }
  589. }
  590. }