Make_ParseLog.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Security.AccessControl;
  10. using System.Security.Principal;
  11. using System.Text;
  12. using System.Web.Services.Description;
  13. using System.Web.UI.WebControls;
  14. using System.Windows.Forms;
  15. using UAS_MES_NEW.CustomControl.ButtonUtil;
  16. using UAS_MES_NEW.DataOperate;
  17. using UAS_MES_NEW.Entity;
  18. using UAS_MES_NEW.PublicMethod;
  19. namespace UAS_MES_NEW.Make
  20. {
  21. public partial class Make_ParseLog : Form
  22. {
  23. public Make_ParseLog()
  24. {
  25. InitializeComponent();
  26. }
  27. FileSystemWatcher watcher;
  28. LogStringBuilder sql = new LogStringBuilder();
  29. DataTable Dbfind;
  30. DataTable dt;
  31. DataHelper dh;
  32. string currFileType = "", equiType = "";
  33. string SN, omakeCode, oMsid, oErrorMessage = "";
  34. List<string> fileList = new List<string>();
  35. Timer ChangeWoTimer;
  36. string outFileMsg;
  37. private void Make_ParseLog_Load(object sender, EventArgs e)
  38. {
  39. dh = SystemInf.dh;
  40. Choose.Enabled = false;
  41. //fileList.Add("E:\\AOIMes\\Mes");
  42. //fileList.Add("E:\\UAS");
  43. //fileList.Add("");
  44. fileList.Add("E:\\cnc图片");
  45. ChangeWoTimer = new Timer();
  46. ChangeWoTimer.Interval = 30000;
  47. ChangeWoTimer.Tick += ChangeWoFunc;
  48. watcher = new FileSystemWatcher();
  49. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
  50. watcher.Created += OnFileCreated;
  51. watcher.Changed += OnFileChanged;
  52. /*watcher.Deleted += OnFileChanged;
  53. watcher.Renamed += OnFileChanged;*/
  54. //设置锁定工单
  55. LockMakeCode.GetMakeCodeCtl(ma_code);
  56. ma_code.SetLockCheckBox(LockMakeCode);
  57. //工单号放大镜配置
  58. ma_code.TableName = "make left join product on ma_prodcode=pr_code";
  59. ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称";
  60. ma_code.FormName = Name;
  61. ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" };
  62. ma_code.Condition = "ma_statuscode='STARTED'";
  63. ma_code.DbChange += Ma_code_DbChange;
  64. }
  65. private void Ma_code_DbChange(object sender, EventArgs e)
  66. {
  67. Dbfind = ma_code.ReturnData;
  68. BaseUtil.SetFormValue(this.Controls, Dbfind);
  69. //获取工单的其他信息
  70. sql.Clear();
  71. sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,");
  72. sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on ");
  73. sql.Append("mcd_maid=ma_id left join product on pr_code=ma_prodcode where ma_code='" + ma_code.Text + "' and mcd_stepcode='" + User.CurrentStepCode + "'");
  74. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  75. if (dt.Rows.Count > 0)
  76. {
  77. BaseUtil.SetFormValue(this.Controls, dt);
  78. }
  79. }
  80. private void Device_SelectedIndexChanged(object sender, EventArgs e)
  81. {
  82. if (Device.SelectedIndex == -1) return;
  83. if(ChangeWoTimer.Enabled) ChangeWoTimer.Stop();
  84. onWatch.Enabled = true;
  85. FileBox.Visible = false;
  86. switch (Device.Text)
  87. {
  88. case "AOI设备":
  89. currFileType = "Txt";
  90. equiType = "AOI";
  91. /*ChangeWoTimer.Start();
  92. ChangeWoFunc(null, null);*/
  93. break;
  94. case "Xray设备":
  95. currFileType = "jpg";
  96. equiType = "Xray";
  97. onWatch.Enabled = false;
  98. FileBox.Visible = true;
  99. break;
  100. case "CCD设备":
  101. currFileType = "jpg";
  102. equiType = "CCD";
  103. break;
  104. }
  105. txtPath.Text = fileList[Device.SelectedIndex];
  106. txtPath.Focus();
  107. txtPath.SelectAll();
  108. ma_code.Enabled = true;
  109. Choose.Enabled = true;
  110. txtPath.Enabled = false;
  111. }
  112. private void Choose_Click(object sender, EventArgs e)
  113. {
  114. using (var dialog = new FolderBrowserDialog())
  115. {
  116. if (dialog.ShowDialog() == DialogResult.OK)
  117. {
  118. txtPath.Text = dialog.SelectedPath;
  119. txtPath.Enabled = false;
  120. Device.Enabled = false;
  121. watcher.EnableRaisingEvents = false;
  122. }
  123. }
  124. }
  125. private void claerBtn_Click(object sender, EventArgs e)
  126. {
  127. lstFiles.Items.Clear();
  128. }
  129. private void allParse_Click(object sender, EventArgs e)
  130. {
  131. if (String.IsNullOrEmpty(ma_code.Text))
  132. {
  133. ma_code.Focus();
  134. MessageBox.Show(this.ParentForm, "请选择归属工单", "提示");
  135. return;
  136. }
  137. if (Device.SelectedIndex == -1)
  138. {
  139. Device.Focus();
  140. Device.SelectAll();
  141. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  142. return;
  143. }
  144. if (String.IsNullOrEmpty(txtPath.Text))
  145. {
  146. txtPath.Focus();
  147. txtPath.SelectAll();
  148. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  149. return;
  150. }
  151. string[] txtFiles;
  152. if (equiType == "Xray")
  153. {
  154. txtFiles = Directory.GetDirectories(txtPath.Text);
  155. if (txtFiles.Length == 0)
  156. {
  157. LogMessage(0, $"当前路径{txtPath.Text},没有{equiType}设备输出的文件夹");
  158. return;
  159. }
  160. }
  161. else
  162. {
  163. txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  164. if (txtFiles.Length == 0)
  165. {
  166. LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  167. return;
  168. }
  169. }
  170. RefreshFileList();
  171. }
  172. private void onWatch_Click(object sender, EventArgs e)
  173. {
  174. if (String.IsNullOrEmpty(ma_code.Text))
  175. {
  176. ma_code.Focus();
  177. MessageBox.Show(this.ParentForm, "请选择归属工单", "提示");
  178. return;
  179. }
  180. if (Device.SelectedIndex == -1)
  181. {
  182. Device.Focus();
  183. Device.SelectAll();
  184. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  185. return;
  186. }
  187. if (String.IsNullOrEmpty(txtPath.Text))
  188. {
  189. txtPath.Focus();
  190. txtPath.SelectAll();
  191. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  192. return;
  193. }
  194. try
  195. {
  196. watcher.Path = txtPath.Text;
  197. watcher.Filter = $"*.{currFileType}";
  198. if (onWatch.Text == "开启解析")
  199. {
  200. watcher.EnableRaisingEvents = true;
  201. onWatch.Text = "关闭解析";
  202. }
  203. else
  204. {
  205. watcher.EnableRaisingEvents = false;
  206. onWatch.Text = "开启解析";
  207. }
  208. }
  209. catch (Exception ex)
  210. {
  211. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  212. }
  213. }
  214. private void OnFileCreated(object sender, FileSystemEventArgs e)
  215. {
  216. RefreshFileList();
  217. }
  218. private void OnFileChanged(object sender, FileSystemEventArgs e)
  219. {
  220. if (e.ChangeType == WatcherChangeTypes.Changed)
  221. {
  222. RefreshFileList();
  223. }
  224. }
  225. private void RefreshFileList()
  226. {
  227. if (lstFiles.InvokeRequired)
  228. {
  229. lstFiles.Invoke(new Action(RefreshFileList));
  230. lstFiles.BeginInvoke(new Action(RefreshFileList));
  231. return;
  232. }
  233. try
  234. {
  235. if (!Directory.Exists(txtPath.Text))
  236. {
  237. LogMessage(0, $"目录不存在: {txtPath.Text}");
  238. return;
  239. }
  240. string[] txtFiles;
  241. if (equiType == "Xray")
  242. {
  243. txtFiles = Directory.GetDirectories(txtPath.Text);
  244. }
  245. else
  246. {
  247. txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  248. }
  249. if (txtFiles.Length == 0)
  250. {
  251. return;
  252. }
  253. foreach (string file in txtFiles)
  254. {
  255. if (equiType == "Xray")
  256. {
  257. if (Path.GetFileName(file).Contains("Log_")) continue;
  258. if (!Directory.Exists(file))
  259. {
  260. LogMessage(0, $"文件夹不存在: {file}");
  261. }
  262. outFileMsg = CheckFolderPermissions(file);
  263. if (outFileMsg != "OK")
  264. {
  265. if(!outFileMsg.Contains("文件被占用"))
  266. {
  267. LogMessage(0, outFileMsg);
  268. }
  269. continue;
  270. }
  271. }else if (equiType == "CCD")
  272. {
  273. outFileMsg = CheckFileAccess(file);
  274. if (outFileMsg != "OK")
  275. {
  276. //LogMessage(0, outFileMsg);
  277. //continue;
  278. }
  279. }
  280. else
  281. {
  282. if (!File.Exists(file))
  283. {
  284. LogMessage(0, $"文件不存在: {file}");
  285. }
  286. if (File.ReadAllText(file).Length == 0)
  287. {
  288. continue;
  289. }
  290. }
  291. if (equiType == "AOI")
  292. {
  293. using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  294. using (StreamReader SR = new StreamReader(fileStream, Encoding.GetEncoding("GBK")))
  295. {
  296. string Content = SR.ReadToEnd();
  297. SR.Close();
  298. SR.Dispose();
  299. List<Log> logArr = new List<Log>() { };
  300. string[] lines = Content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  301. int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
  302. Log itemLog = new Log() { };
  303. foreach (var item in lines)
  304. {
  305. if (string.IsNullOrEmpty(item)) continue;
  306. if (Array.IndexOf(lines, item) == 1) itemLog.SN = item.Split(':')[1].ToString().Trim().Replace(";", ";");
  307. if (Array.IndexOf(lines, item) == 2) itemLog.TestTime = item.Split(':')[1].Split('.')[0].ToString().Trim();
  308. if (Array.IndexOf(lines, item) == 3) itemLog.Result = item.Split(':')[1].ToString().Trim();
  309. if (Array.IndexOf(lines, item) == 4) itemLog.Side = item.Split(':')[1].ToString().Trim();
  310. if (item.IndexOf("元件位置") > -1)
  311. {
  312. LogItem list = new LogItem();
  313. int ind = Array.IndexOf(lines, item);
  314. list.Location = lines[ind].Split(':')[1].ToString().Trim();
  315. list.ReelNo = lines[ind + 1].Split(':')[1].ToString().Trim();
  316. list.FirstType = lines[ind + 2].Split(':')[1].ToString().Trim();
  317. list.SceondType = lines[ind + 3].Split(':')[1].ToString().Trim();
  318. list.Name = lines[ind + 4].Split(':')[1].ToString().Trim();
  319. itemLog.LogItemList.Add(list);
  320. }
  321. }
  322. logArr.Add(itemLog);
  323. if (logArr.Count == 0)
  324. {
  325. break;
  326. }
  327. if (InsertDb(logArr, file, fileNum))
  328. {
  329. if (ConsoleLog(Content, file, logArr[0].SN))
  330. {
  331. File.WriteAllText(file, string.Empty);
  332. outFileMsg = CheckFileAccess(file);
  333. if (outFileMsg == "OK")
  334. {
  335. File.Delete(file);
  336. }
  337. }
  338. }
  339. }
  340. }
  341. else if (equiType == "Xray")
  342. {
  343. string ok = Path.Combine(file, "OK");
  344. string ng = Path.Combine(file, "NG");
  345. string na = Path.Combine(file, "NA");
  346. string[] okPath = Directory.GetDirectories(ok);
  347. string[] ngPath = Directory.GetDirectories(ng);
  348. string[] naPath = Directory.GetDirectories(na);
  349. List<string> pathList = new List<string> { };
  350. if(okPath.Length > 0)
  351. {
  352. foreach(string item in okPath)
  353. {
  354. pathList.Add(item);
  355. }
  356. }
  357. if(ngPath.Length > 0)
  358. {
  359. foreach (string item in ngPath)
  360. {
  361. pathList.Add(item);
  362. }
  363. }
  364. if (naPath.Length > 0)
  365. {
  366. foreach (string item in naPath)
  367. {
  368. pathList.Add(item);
  369. }
  370. }
  371. foreach(string currPath in pathList)
  372. {
  373. string[] floderFile = Directory.GetFiles(currPath, $"*.{currFileType}");
  374. foreach (string floderFileItem in floderFile)
  375. {
  376. SN = Path.GetFileName(floderFileItem).Split('_')[0];
  377. if(SN.ToLower() == "none")
  378. {
  379. SN = Path.GetFileName(currPath).Split('_')[1];
  380. if (UploadImageToFtp(floderFileItem, SN))
  381. {
  382. string time = File.GetCreationTime(floderFileItem).ToString("yyyy:MM:dd HH:mm:ss");
  383. dh.ExecuteSql($@"UPDATE xraytest SET xt_url = 'http://192.168.41.232:8098/ftp/Xray/{DateTime.Now.ToString("yyyyMMdd")}/{SN}/{Path.GetFileName(floderFileItem)}',
  384. xt_macode = '{ma_code.Text.Trim()}' WHERE checkdate = to_date('{time}','YYYY:MM:DD HH24:MI:SS')", "update");
  385. }
  386. }
  387. else
  388. {
  389. if (UploadImageToFtp(floderFileItem, SN))
  390. {
  391. dh.ExecuteSql($@"UPDATE xraytest SET xt_url = 'http://192.168.41.232:8098/ftp/Xray/{DateTime.Now.ToString("yyyyMMdd")}/{SN}/{Path.GetFileName(floderFileItem)}',
  392. xt_macode = '{ma_code.Text.Trim()}' WHERE barcode = '{SN}'", "update");
  393. }
  394. }
  395. }
  396. }
  397. string newFloderName = Path.GetDirectoryName(file);
  398. Directory.Move(file, Path.Combine(newFloderName, "Log_" + Path.GetFileName(file)));
  399. }
  400. else if(equiType == "CCD")
  401. {
  402. foreach (var fileItem in txtFiles)
  403. {
  404. string imageName = Path.GetFileName(fileItem);
  405. string iName = imageName.Split('_')[0];
  406. if (iName.Length > 14)
  407. {
  408. SN = iName.Length > 14 ? iName.Substring(3) : "";
  409. }
  410. if (imageName.ToUpper().Contains("NG"))
  411. {
  412. if (txtFiles.Length != 3)
  413. {
  414. SN = "";
  415. return;
  416. }
  417. }
  418. else if(imageName.ToUpper().Contains("OK"))
  419. {
  420. if (txtFiles.Length != 2)
  421. {
  422. SN = "";
  423. return;
  424. }
  425. }
  426. }
  427. string parentPath = Path.GetDirectoryName(file);
  428. string newFolderPath = Path.Combine(parentPath, "Logs");
  429. if (!Directory.Exists(newFolderPath))
  430. {
  431. Directory.CreateDirectory(newFolderPath);
  432. }
  433. string changeName = Path.Combine(newFolderPath, SN);
  434. if (!Directory.Exists(changeName))
  435. {
  436. Directory.CreateDirectory(changeName);
  437. }
  438. string result = Path.GetFileName(file).Split('_')[0];
  439. if (result.ToUpper().Contains("NG"))
  440. {
  441. if (UploadImageToFtp(file, SN))
  442. {
  443. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  444. VALUES (steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text}','{User.UserSourceCode}', sysdate,'CCD', 'http://192.168.1.5:8088/ftp/ccd/{SN}/{Path.GetFileName(file)}' )", "insert");
  445. }
  446. }
  447. string targetFile = Path.Combine(changeName, Path.GetFileName(file));
  448. if (File.Exists(targetFile))
  449. {
  450. File.Delete(targetFile);
  451. }
  452. File.Move(file, targetFile);
  453. }
  454. }
  455. if (equiType == "CCD")
  456. {
  457. LogMessage(1, $"序列号: {SN} 图片已处理");
  458. }
  459. }
  460. catch (Exception ex)
  461. {
  462. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  463. }
  464. }
  465. private bool InsertDb(List<Log> logs, string PathName, int fileNum)
  466. {
  467. try
  468. {
  469. StringBuilder sql = new StringBuilder();
  470. StringBuilder details = new StringBuilder();
  471. List<string> param = new List<string>() { };
  472. foreach (var item in logs)
  473. {
  474. dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{item.SN}' AND mp_sourcecode = 'AOI'", "select");
  475. if (dt.Rows.Count > 0)
  476. {
  477. LogMessage(1, $"序列号:{item.SN}已经过站并记录测试信息");
  478. continue;
  479. }
  480. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  481. {
  482. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", item.Result.ToUpper() == "PASS" ? "OK" :"NG", User.UserCode, out oErrorMessage))
  483. {
  484. string outMsg = "";
  485. param.Add(omakeCode);
  486. param.Add(item.SN);
  487. param.Add(User.UserSourceCode);
  488. param.Add(User.UserName);
  489. param.Add(User.CurrentStepCode);
  490. param.Add(item.Result.ToUpper());
  491. param.Add(item.TestTime);
  492. param.Add(item.Side);
  493. param.Add(equiType);
  494. details.Clear();
  495. foreach (LogItem LI in item.LogItemList)
  496. {
  497. details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
  498. }
  499. param.Add(details.ToString());
  500. param.Add(outMsg);
  501. string[] paramList = param.ToArray();
  502. dh.CallProcedure("CS_INSERT_TESTDETAILS", ref paramList);
  503. if (paramList[10].Substring(0, 2) == "OK")
  504. {
  505. LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
  506. }
  507. else
  508. {
  509. LogMessage(1, paramList[8]);
  510. }
  511. param.Clear();
  512. if (logs.IndexOf(item) == logs.Count - 1)
  513. {
  514. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
  515. return true;
  516. }
  517. }
  518. else
  519. {
  520. LogMessage(0, $"处理过站NG:{oErrorMessage}");
  521. break;
  522. }
  523. }
  524. else
  525. {
  526. LogMessage(0, $"过站核对NG:{oErrorMessage}");
  527. break;
  528. }
  529. }
  530. return false;
  531. }
  532. catch (Exception ex)
  533. {
  534. LogMessage(0, $"Error,处理解析写入: {ex.Message}");
  535. return false;
  536. }
  537. }
  538. private void ChangeWoFunc(object sender, EventArgs e)
  539. {
  540. try
  541. {
  542. sql.Clear();
  543. sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
  544. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  545. if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
  546. {
  547. ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
  548. return;
  549. }
  550. LogMessage(0, $"NG,自动识别更新工单");
  551. }
  552. catch (Exception ex)
  553. {
  554. LogMessage(0, $"Error,自动切换工单: {ex.Message}");
  555. }
  556. }
  557. private bool ConsoleLog(string Content, string PathName,string SN)
  558. {
  559. try
  560. {
  561. string sourcePaht = Path.GetDirectoryName(PathName);
  562. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  563. string newFolderName = "Logs";
  564. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  565. if (!Directory.Exists(newFolderPath))
  566. {
  567. Directory.CreateDirectory(newFolderPath);
  568. }
  569. string newFileName = "Log_" + Path.GetFileName(changeName);
  570. string newFilePath = Path.Combine(newFolderPath, newFileName);
  571. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  572. return true;
  573. }
  574. catch (Exception ex)
  575. {
  576. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  577. return false;
  578. }
  579. }
  580. private void LogMessage(int type, string message)
  581. {
  582. if (type == 0)
  583. {
  584. if (lstFiles.InvokeRequired)
  585. {
  586. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  587. return;
  588. }
  589. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  590. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  591. }
  592. else
  593. {
  594. if (lstOk.InvokeRequired)
  595. {
  596. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  597. return;
  598. }
  599. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  600. lstOk.TopIndex = lstOk.Items.Count - 1;
  601. }
  602. }
  603. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  604. {
  605. if (e.Index < 0) return;
  606. e.DrawBackground();
  607. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  608. Brush color = Brushes.Black;
  609. if (txt.Contains("NG"))
  610. {
  611. color = Brushes.Red;
  612. }
  613. else if (txt.Contains("ERROR"))
  614. {
  615. color = Brushes.Red;
  616. }
  617. else
  618. {
  619. color = Brushes.Green;
  620. }
  621. e.DrawFocusRectangle();
  622. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  623. }
  624. public bool UploadImageToFtp(string localFilePath, string Sn)
  625. {
  626. string ftpServer;
  627. ftpServer = "ftp://192.168.41.232:21/Xray/";
  628. string username = "vsftpd";
  629. string password = "vsftpd7de41958Jp";
  630. string ftpTimePath = $"{ftpServer.TrimEnd('/')}/{DateTime.Now.ToString("yyyyMMdd")}";
  631. string outResult = CreateFtpDirectoryIfNotExists(ftpTimePath, username, password);
  632. if (outResult.Substring(0, 2) != "OK")
  633. {
  634. LogMessage(0, outResult);
  635. return false;
  636. }
  637. string ftpFullPath = $"{ftpTimePath}/{Sn}";
  638. outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
  639. if (outResult.Substring(0, 2) != "OK")
  640. {
  641. LogMessage(0, outResult);
  642. return false;
  643. }
  644. string remoteFileName = Path.GetFileName(localFilePath);
  645. string uri = $"{ftpFullPath}/{remoteFileName}";
  646. try
  647. {
  648. var request = (FtpWebRequest)WebRequest.Create(uri);
  649. request.Method = WebRequestMethods.Ftp.UploadFile;
  650. request.Credentials = new NetworkCredential(username, password);
  651. request.UsePassive = true;
  652. request.UseBinary = true;
  653. request.KeepAlive = false;
  654. using (var fileStream = File.OpenRead(localFilePath))
  655. using (var requestStream = request.GetRequestStream())
  656. {
  657. byte[] buffer = new byte[4096];
  658. int bytesRead;
  659. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  660. {
  661. requestStream.Write(buffer, 0, bytesRead);
  662. }
  663. }
  664. using (var response = (FtpWebResponse)request.GetResponse())
  665. {
  666. LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
  667. return true;
  668. }
  669. }
  670. catch (WebException ex)
  671. {
  672. if (ex.Response is FtpWebResponse response)
  673. {
  674. LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  675. }
  676. else
  677. {
  678. LogMessage(0, $"NG,Web异常: {ex.Message}");
  679. }
  680. return false;
  681. }
  682. catch (Exception ex)
  683. {
  684. LogMessage(0, $"NG,上传失败: {ex.Message}");
  685. return false;
  686. }
  687. }
  688. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  689. {
  690. try
  691. {
  692. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  693. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  694. request.Credentials = new NetworkCredential(username, password);
  695. request.UsePassive = true;
  696. request.UseBinary = true;
  697. request.KeepAlive = false;
  698. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  699. {
  700. response.Close();
  701. return "OK,目录创建成功: " + response.StatusDescription;
  702. }
  703. }
  704. catch (WebException ex)
  705. {
  706. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  707. {
  708. return "OK,目录已存在: " + response.StatusDescription;
  709. }
  710. else
  711. {
  712. return "NG,创建目录时发生错误: " + ex.Message;
  713. }
  714. }
  715. }
  716. private void Delete_Click(object sender, EventArgs e)
  717. {
  718. if (!Directory.Exists(txtPath.Text))
  719. {
  720. LogMessage(0, $"删除路径不存在: {txtPath.Text}");
  721. return;
  722. }
  723. List<string> DeleteList = new List<string>() { };
  724. if (!string.IsNullOrEmpty(SN1.Text)) DeleteList.Add("1-1_" + SN1.Text);
  725. if (!string.IsNullOrEmpty(SN2.Text)) DeleteList.Add("1-2_" + SN2.Text);
  726. if (!string.IsNullOrEmpty(SN3.Text)) DeleteList.Add("1-3_" + SN3.Text);
  727. if (!string.IsNullOrEmpty(SN4.Text)) DeleteList.Add("2-1_" + SN4.Text);
  728. if (!string.IsNullOrEmpty(SN5.Text)) DeleteList.Add("2-2_" + SN5.Text);
  729. if (!string.IsNullOrEmpty(SN6.Text)) DeleteList.Add("2-3_" + SN6.Text);
  730. string DeletePath;
  731. int DeleteCount = 0;
  732. foreach (var item in DeleteList)
  733. {
  734. DeletePath = Path.Combine(txtPath.Text, item);
  735. if (DeletePath == txtPath.Text)
  736. {
  737. LogMessage(0, $"NG,路径{DeletePath}中,没有 {item} 文件夹");
  738. continue;
  739. }
  740. if (Directory.Exists(DeletePath))
  741. {
  742. try
  743. {
  744. Directory.Delete(DeletePath);
  745. }
  746. catch (IOException ex)
  747. {
  748. LogMessage(0, $"NG,文件夹{item}存有文件,{ex.Message}");
  749. continue;
  750. }
  751. catch (Exception ex)
  752. {
  753. LogMessage(0, $"NG,删除异常,{ex.Message}");
  754. continue;
  755. }
  756. DeleteCount++;
  757. if (SN1.Text == item) SN1.Text = "";
  758. if (SN2.Text == item) SN2.Text = "";
  759. if (SN3.Text == item) SN3.Text = "";
  760. if (SN4.Text == item) SN4.Text = "";
  761. if (SN5.Text == item) SN5.Text = "";
  762. if (SN6.Text == item) SN6.Text = "";
  763. }
  764. }
  765. if(DeleteCount != 0)
  766. {
  767. LogMessage(0, $"一键删除文件夹成功,共 {DeleteCount}个");
  768. return;
  769. }
  770. else
  771. {
  772. LogMessage(0, $"NG,请扫描SN序列号删除文件夹");
  773. }
  774. }
  775. private void Clear_Click(object sender, EventArgs e)
  776. {
  777. SN1.Text = "";
  778. SN2.Text = "";
  779. SN3.Text = "";
  780. SN4.Text = "";
  781. SN5.Text = "";
  782. SN6.Text = "";
  783. SN1.Focus();
  784. SN1.SelectAll();
  785. }
  786. private void Generate_Click(object sender, EventArgs e)
  787. {
  788. if (!Directory.Exists(txtPath.Text))
  789. {
  790. LogMessage(0, $"NG,生成路径不存在: {txtPath.Text}");
  791. return;
  792. }
  793. List<string> GenerateList = new List<string>() { };
  794. if (!string.IsNullOrEmpty(SN1.Text)) GenerateList.Add("1-1_" + SN1.Text);
  795. if (!string.IsNullOrEmpty(SN2.Text)) GenerateList.Add("1-2_" + SN2.Text);
  796. if (!string.IsNullOrEmpty(SN3.Text)) GenerateList.Add("1-3_" + SN3.Text);
  797. if (!string.IsNullOrEmpty(SN4.Text)) GenerateList.Add("2-1_" + SN4.Text);
  798. if (!string.IsNullOrEmpty(SN5.Text)) GenerateList.Add("2-2_" + SN5.Text);
  799. if (!string.IsNullOrEmpty(SN6.Text)) GenerateList.Add("2-3_" + SN6.Text);
  800. string GeneratePath;
  801. int GenerateCount = 0;
  802. foreach (var item in GenerateList)
  803. {
  804. GeneratePath = Path.Combine(txtPath.Text, item);
  805. if (GeneratePath == txtPath.Text)
  806. {
  807. LogMessage(0, $"NG,请扫描SN序列号创建文件夹");
  808. continue;
  809. }
  810. if (Directory.Exists(GeneratePath))
  811. {
  812. LogMessage(0, $"NG,路径{txtPath.Text}已有{item}文件夹");
  813. continue;
  814. }
  815. Directory.CreateDirectory(GeneratePath);
  816. GenerateCount++;
  817. }
  818. if(GenerateCount != 0) LogMessage(0, $"一键生成文件夹成功,共 {GenerateCount}个");
  819. }
  820. private void SN1_KeyDown(object sender, KeyEventArgs e)
  821. {
  822. if (e.KeyCode != Keys.Enter) return;
  823. if (string.IsNullOrEmpty(SN1.Text)) return;
  824. SN2.Focus();
  825. SN2.SelectAll();
  826. }
  827. private void SN2_KeyDown(object sender, KeyEventArgs e)
  828. {
  829. if (e.KeyCode != Keys.Enter) return;
  830. if (string.IsNullOrEmpty(SN2.Text)) return;
  831. SN3.Focus();
  832. SN3.SelectAll();
  833. }
  834. private void SN3_KeyDown(object sender, KeyEventArgs e)
  835. {
  836. if (e.KeyCode != Keys.Enter) return;
  837. if (string.IsNullOrEmpty(SN3.Text)) return;
  838. SN4.Focus();
  839. SN4.SelectAll();
  840. }
  841. private void SN4_KeyDown(object sender, KeyEventArgs e)
  842. {
  843. if (e.KeyCode != Keys.Enter) return;
  844. if (string.IsNullOrEmpty(SN4.Text)) return;
  845. SN5.Focus();
  846. SN5.SelectAll();
  847. }
  848. private void SN5_KeyDown(object sender, KeyEventArgs e)
  849. {
  850. if (e.KeyCode != Keys.Enter) return;
  851. if (string.IsNullOrEmpty(SN5.Text)) return;
  852. SN6.Focus();
  853. SN6.SelectAll();
  854. }
  855. private void SN6_KeyDown(object sender, KeyEventArgs e)
  856. {
  857. if (e.KeyCode != Keys.Enter) return;
  858. if (string.IsNullOrEmpty(SN6.Text)) return;
  859. Generate.Focus();
  860. }
  861. public string CheckFileAccess(string filePath)
  862. {
  863. try
  864. {
  865. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  866. {
  867. return "OK";
  868. }
  869. }
  870. catch (IOException ex)
  871. {
  872. return "NG,文件被占用: " + ex.Message;
  873. }
  874. catch (UnauthorizedAccessException ex)
  875. {
  876. return "NG,权限不足,无法访问文件: " + ex.Message;
  877. }
  878. catch (Exception ex)
  879. {
  880. return "NG," + ex.Message;
  881. }
  882. }
  883. public string CheckFolderPermissions(string path)
  884. {
  885. try
  886. {
  887. DirectorySecurity security = Directory.GetAccessControl(path);
  888. AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
  889. WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
  890. foreach (FileSystemAccessRule rule in rules)
  891. {
  892. if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
  893. {
  894. Console.WriteLine($" {rule.IdentityReference.Value}");
  895. Console.WriteLine($"权限类型: {rule.AccessControlType}");
  896. Console.WriteLine($"具体权限: {rule.FileSystemRights}");
  897. Console.WriteLine($"是否继承: {rule.IsInherited}");
  898. }
  899. }
  900. return "OK";
  901. }
  902. catch (UnauthorizedAccessException ex)
  903. {
  904. return $"NG,无权限访问文件夹: {ex.Message}";
  905. }
  906. catch (DirectoryNotFoundException)
  907. {
  908. return "NG,文件夹不存在";
  909. }
  910. catch (Exception ex)
  911. {
  912. return "NG," + ex.Message;
  913. }
  914. }
  915. public class Log
  916. {
  917. public string SN { set; get; }
  918. public string Result { set; get; }
  919. public string TestTime { set; get; }
  920. public string Side { set; get; }
  921. public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
  922. }
  923. public class LogItem
  924. {
  925. public string Location { set; get; }
  926. public string ReelNo { set; get; }
  927. public string FirstType { set; get; }
  928. public string SceondType { set; get; }
  929. public string Name { set; get; }
  930. }
  931. }
  932. }