Make_FirstInspect.cs 28 KB

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