Make_ParseLog.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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. List<string> pathList = new List<string> { };
  347. if (Directory.Exists(ok))
  348. {
  349. string[] okPath = Directory.GetDirectories(ok);
  350. if (okPath.Length > 0)
  351. {
  352. foreach (string item in okPath)
  353. {
  354. pathList.Add(item);
  355. }
  356. }
  357. }
  358. if (Directory.Exists(ng))
  359. {
  360. string[] ngPath = Directory.GetDirectories(ng);
  361. if (ngPath.Length > 0)
  362. {
  363. foreach (string item in ngPath)
  364. {
  365. pathList.Add(item);
  366. }
  367. }
  368. }
  369. if (Directory.Exists(na))
  370. {
  371. string[] naPath = Directory.GetDirectories(na);
  372. if (naPath.Length > 0)
  373. {
  374. foreach (string item in naPath)
  375. {
  376. pathList.Add(item);
  377. }
  378. }
  379. }
  380. foreach(string currPath in pathList)
  381. {
  382. string[] floderFile = Directory.GetFiles(currPath, $"*.{currFileType}");
  383. foreach (string floderFileItem in floderFile)
  384. {
  385. SN = Path.GetFileName(floderFileItem).Split('_')[0];
  386. if(SN.ToLower() == "none")
  387. {
  388. SN = Path.GetFileName(currPath).Split('_')[1];
  389. if (UploadImageToFtp(floderFileItem, SN))
  390. {
  391. string time = File.GetCreationTime(floderFileItem).ToString("yyyy:MM:dd HH:mm:ss");
  392. dh.ExecuteSql($@"UPDATE xraytest SET xt_url = 'http://192.168.41.232:8098/ftp/Xray/{DateTime.Now.ToString("yyyyMMdd")}/{SN}/{Path.GetFileName(floderFileItem)}',
  393. xt_macode = '{ma_code.Text.Trim()}' WHERE checkdate = to_date('{time}','YYYY:MM:DD HH24:MI:SS')", "update");
  394. }
  395. }
  396. else
  397. {
  398. if (UploadImageToFtp(floderFileItem, SN))
  399. {
  400. dh.ExecuteSql($@"UPDATE xraytest SET xt_url = 'http://192.168.41.232:8098/ftp/Xray/{DateTime.Now.ToString("yyyyMMdd")}/{SN}/{Path.GetFileName(floderFileItem)}',
  401. xt_macode = '{ma_code.Text.Trim()}' WHERE barcode = '{SN}'", "update");
  402. }
  403. }
  404. }
  405. }
  406. string newFloderName = Path.GetDirectoryName(file);
  407. Directory.Move(file, Path.Combine(newFloderName, "Log_" + Path.GetFileName(file)));
  408. }
  409. else if(equiType == "CCD")
  410. {
  411. foreach (var fileItem in txtFiles)
  412. {
  413. string imageName = Path.GetFileName(fileItem);
  414. string iName = imageName.Split('_')[0];
  415. if (iName.Length > 14)
  416. {
  417. SN = iName.Length > 14 ? iName.Substring(3) : "";
  418. }
  419. if (imageName.ToUpper().Contains("NG"))
  420. {
  421. if (txtFiles.Length != 3)
  422. {
  423. SN = "";
  424. return;
  425. }
  426. }
  427. else if(imageName.ToUpper().Contains("OK"))
  428. {
  429. if (txtFiles.Length != 2)
  430. {
  431. SN = "";
  432. return;
  433. }
  434. }
  435. }
  436. string parentPath = Path.GetDirectoryName(file);
  437. string newFolderPath = Path.Combine(parentPath, "Logs");
  438. if (!Directory.Exists(newFolderPath))
  439. {
  440. Directory.CreateDirectory(newFolderPath);
  441. }
  442. string changeName = Path.Combine(newFolderPath, SN);
  443. if (!Directory.Exists(changeName))
  444. {
  445. Directory.CreateDirectory(changeName);
  446. }
  447. string result = Path.GetFileName(file).Split('_')[0];
  448. if (result.ToUpper().Contains("NG"))
  449. {
  450. if (UploadImageToFtp(file, SN))
  451. {
  452. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  453. 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");
  454. }
  455. }
  456. string targetFile = Path.Combine(changeName, Path.GetFileName(file));
  457. if (File.Exists(targetFile))
  458. {
  459. File.Delete(targetFile);
  460. }
  461. File.Move(file, targetFile);
  462. }
  463. }
  464. if (equiType == "CCD")
  465. {
  466. LogMessage(1, $"序列号: {SN} 图片已处理");
  467. }
  468. }
  469. catch (Exception ex)
  470. {
  471. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  472. }
  473. }
  474. private bool InsertDb(List<Log> logs, string PathName, int fileNum)
  475. {
  476. try
  477. {
  478. StringBuilder sql = new StringBuilder();
  479. StringBuilder details = new StringBuilder();
  480. List<string> param = new List<string>() { };
  481. foreach (var item in logs)
  482. {
  483. dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{item.SN}' AND mp_sourcecode = 'AOI'", "select");
  484. if (dt.Rows.Count > 0)
  485. {
  486. LogMessage(1, $"序列号:{item.SN}已经过站并记录测试信息");
  487. continue;
  488. }
  489. if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
  490. {
  491. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", item.Result.ToUpper() == "PASS" ? "OK" :"NG", User.UserCode, out oErrorMessage))
  492. {
  493. string outMsg = "";
  494. param.Add(omakeCode);
  495. param.Add(item.SN);
  496. param.Add(User.UserSourceCode);
  497. param.Add(User.UserName);
  498. param.Add(User.CurrentStepCode);
  499. param.Add(item.Result.ToUpper());
  500. param.Add(item.TestTime);
  501. param.Add(item.Side);
  502. param.Add(equiType);
  503. details.Clear();
  504. foreach (LogItem LI in item.LogItemList)
  505. {
  506. details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
  507. }
  508. param.Add(details.ToString());
  509. param.Add(outMsg);
  510. string[] paramList = param.ToArray();
  511. dh.CallProcedure("CS_INSERT_TESTDETAILS", ref paramList);
  512. if (paramList[10].Substring(0, 2) == "OK")
  513. {
  514. LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
  515. }
  516. else
  517. {
  518. LogMessage(1, paramList[8]);
  519. }
  520. param.Clear();
  521. if (logs.IndexOf(item) == logs.Count - 1)
  522. {
  523. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
  524. return true;
  525. }
  526. }
  527. else
  528. {
  529. LogMessage(0, $"处理过站NG:{oErrorMessage}");
  530. break;
  531. }
  532. }
  533. else
  534. {
  535. LogMessage(0, $"过站核对NG:{oErrorMessage}");
  536. break;
  537. }
  538. }
  539. return false;
  540. }
  541. catch (Exception ex)
  542. {
  543. LogMessage(0, $"Error,处理解析写入: {ex.Message}");
  544. return false;
  545. }
  546. }
  547. private void ChangeWoFunc(object sender, EventArgs e)
  548. {
  549. try
  550. {
  551. sql.Clear();
  552. sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
  553. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  554. if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
  555. {
  556. ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
  557. return;
  558. }
  559. LogMessage(0, $"NG,自动识别更新工单");
  560. }
  561. catch (Exception ex)
  562. {
  563. LogMessage(0, $"Error,自动切换工单: {ex.Message}");
  564. }
  565. }
  566. private bool ConsoleLog(string Content, string PathName,string SN)
  567. {
  568. try
  569. {
  570. string sourcePaht = Path.GetDirectoryName(PathName);
  571. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  572. string newFolderName = "Logs";
  573. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  574. if (!Directory.Exists(newFolderPath))
  575. {
  576. Directory.CreateDirectory(newFolderPath);
  577. }
  578. string newFileName = "Log_" + Path.GetFileName(changeName);
  579. string newFilePath = Path.Combine(newFolderPath, newFileName);
  580. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  581. return true;
  582. }
  583. catch (Exception ex)
  584. {
  585. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  586. return false;
  587. }
  588. }
  589. private void LogMessage(int type, string message)
  590. {
  591. if (type == 0)
  592. {
  593. if (lstFiles.InvokeRequired)
  594. {
  595. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  596. return;
  597. }
  598. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  599. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  600. }
  601. else
  602. {
  603. if (lstOk.InvokeRequired)
  604. {
  605. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  606. return;
  607. }
  608. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  609. lstOk.TopIndex = lstOk.Items.Count - 1;
  610. }
  611. }
  612. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  613. {
  614. if (e.Index < 0) return;
  615. e.DrawBackground();
  616. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  617. Brush color = Brushes.Black;
  618. if (txt.Contains("NG"))
  619. {
  620. color = Brushes.Red;
  621. }
  622. else if (txt.Contains("ERROR"))
  623. {
  624. color = Brushes.Red;
  625. }
  626. else
  627. {
  628. color = Brushes.Green;
  629. }
  630. e.DrawFocusRectangle();
  631. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  632. }
  633. public bool UploadImageToFtp(string localFilePath, string Sn)
  634. {
  635. string ftpServer;
  636. ftpServer = "ftp://192.168.41.232:21/Xray/";
  637. string username = "vsftpd";
  638. string password = "vsftpd7de41958Jp";
  639. string ftpTimePath = $"{ftpServer.TrimEnd('/')}/{DateTime.Now.ToString("yyyyMMdd")}";
  640. string outResult = CreateFtpDirectoryIfNotExists(ftpTimePath, username, password);
  641. if (outResult.Substring(0, 2) != "OK")
  642. {
  643. LogMessage(0, outResult);
  644. return false;
  645. }
  646. string ftpFullPath = $"{ftpTimePath}/{Sn}";
  647. outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
  648. if (outResult.Substring(0, 2) != "OK")
  649. {
  650. LogMessage(0, outResult);
  651. return false;
  652. }
  653. string remoteFileName = Path.GetFileName(localFilePath);
  654. string uri = $"{ftpFullPath}/{remoteFileName}";
  655. try
  656. {
  657. var request = (FtpWebRequest)WebRequest.Create(uri);
  658. request.Method = WebRequestMethods.Ftp.UploadFile;
  659. request.Credentials = new NetworkCredential(username, password);
  660. request.UsePassive = true;
  661. request.UseBinary = true;
  662. request.KeepAlive = false;
  663. using (var fileStream = File.OpenRead(localFilePath))
  664. using (var requestStream = request.GetRequestStream())
  665. {
  666. byte[] buffer = new byte[4096];
  667. int bytesRead;
  668. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  669. {
  670. requestStream.Write(buffer, 0, bytesRead);
  671. }
  672. }
  673. using (var response = (FtpWebResponse)request.GetResponse())
  674. {
  675. LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
  676. return true;
  677. }
  678. }
  679. catch (WebException ex)
  680. {
  681. if (ex.Response is FtpWebResponse response)
  682. {
  683. LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  684. }
  685. else
  686. {
  687. LogMessage(0, $"NG,Web异常: {ex.Message}");
  688. }
  689. return false;
  690. }
  691. catch (Exception ex)
  692. {
  693. LogMessage(0, $"NG,上传失败: {ex.Message}");
  694. return false;
  695. }
  696. }
  697. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  698. {
  699. try
  700. {
  701. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  702. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  703. request.Credentials = new NetworkCredential(username, password);
  704. request.UsePassive = true;
  705. request.UseBinary = true;
  706. request.KeepAlive = false;
  707. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  708. {
  709. response.Close();
  710. return "OK,目录创建成功: " + response.StatusDescription;
  711. }
  712. }
  713. catch (WebException ex)
  714. {
  715. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  716. {
  717. return "OK,目录已存在: " + response.StatusDescription;
  718. }
  719. else
  720. {
  721. return "NG,创建目录时发生错误: " + ex.Message;
  722. }
  723. }
  724. }
  725. private void Delete_Click(object sender, EventArgs e)
  726. {
  727. if (!Directory.Exists(txtPath.Text))
  728. {
  729. LogMessage(0, $"删除路径不存在: {txtPath.Text}");
  730. return;
  731. }
  732. List<string> DeleteList = new List<string>() { };
  733. if (!string.IsNullOrEmpty(SN1.Text)) DeleteList.Add("1-1_" + SN1.Text);
  734. if (!string.IsNullOrEmpty(SN2.Text)) DeleteList.Add("1-2_" + SN2.Text);
  735. if (!string.IsNullOrEmpty(SN3.Text)) DeleteList.Add("1-3_" + SN3.Text);
  736. if (!string.IsNullOrEmpty(SN4.Text)) DeleteList.Add("2-1_" + SN4.Text);
  737. if (!string.IsNullOrEmpty(SN5.Text)) DeleteList.Add("2-2_" + SN5.Text);
  738. if (!string.IsNullOrEmpty(SN6.Text)) DeleteList.Add("2-3_" + SN6.Text);
  739. string DeletePath;
  740. int DeleteCount = 0;
  741. foreach (var item in DeleteList)
  742. {
  743. DeletePath = Path.Combine(txtPath.Text, item);
  744. if (DeletePath == txtPath.Text)
  745. {
  746. LogMessage(0, $"NG,路径{DeletePath}中,没有 {item} 文件夹");
  747. continue;
  748. }
  749. if (Directory.Exists(DeletePath))
  750. {
  751. try
  752. {
  753. Directory.Delete(DeletePath);
  754. }
  755. catch (IOException ex)
  756. {
  757. LogMessage(0, $"NG,文件夹{item}存有文件,{ex.Message}");
  758. continue;
  759. }
  760. catch (Exception ex)
  761. {
  762. LogMessage(0, $"NG,删除异常,{ex.Message}");
  763. continue;
  764. }
  765. DeleteCount++;
  766. if (SN1.Text == item) SN1.Text = "";
  767. if (SN2.Text == item) SN2.Text = "";
  768. if (SN3.Text == item) SN3.Text = "";
  769. if (SN4.Text == item) SN4.Text = "";
  770. if (SN5.Text == item) SN5.Text = "";
  771. if (SN6.Text == item) SN6.Text = "";
  772. }
  773. }
  774. if(DeleteCount != 0)
  775. {
  776. LogMessage(0, $"一键删除文件夹成功,共 {DeleteCount}个");
  777. return;
  778. }
  779. else
  780. {
  781. LogMessage(0, $"NG,请扫描SN序列号删除文件夹");
  782. }
  783. }
  784. private void Clear_Click(object sender, EventArgs e)
  785. {
  786. SN1.Text = "";
  787. SN2.Text = "";
  788. SN3.Text = "";
  789. SN4.Text = "";
  790. SN5.Text = "";
  791. SN6.Text = "";
  792. SN1.Focus();
  793. SN1.SelectAll();
  794. }
  795. private void Generate_Click(object sender, EventArgs e)
  796. {
  797. if (!Directory.Exists(txtPath.Text))
  798. {
  799. LogMessage(0, $"NG,生成路径不存在: {txtPath.Text}");
  800. return;
  801. }
  802. List<string> GenerateList = new List<string>() { };
  803. if (!string.IsNullOrEmpty(SN1.Text)) GenerateList.Add("1-1_" + SN1.Text);
  804. if (!string.IsNullOrEmpty(SN2.Text)) GenerateList.Add("1-2_" + SN2.Text);
  805. if (!string.IsNullOrEmpty(SN3.Text)) GenerateList.Add("1-3_" + SN3.Text);
  806. if (!string.IsNullOrEmpty(SN4.Text)) GenerateList.Add("2-1_" + SN4.Text);
  807. if (!string.IsNullOrEmpty(SN5.Text)) GenerateList.Add("2-2_" + SN5.Text);
  808. if (!string.IsNullOrEmpty(SN6.Text)) GenerateList.Add("2-3_" + SN6.Text);
  809. string GeneratePath;
  810. int GenerateCount = 0;
  811. foreach (var item in GenerateList)
  812. {
  813. GeneratePath = Path.Combine(txtPath.Text, item);
  814. if (GeneratePath == txtPath.Text)
  815. {
  816. LogMessage(0, $"NG,请扫描SN序列号创建文件夹");
  817. continue;
  818. }
  819. if (Directory.Exists(GeneratePath))
  820. {
  821. LogMessage(0, $"NG,路径{txtPath.Text}已有{item}文件夹");
  822. continue;
  823. }
  824. Directory.CreateDirectory(GeneratePath);
  825. GenerateCount++;
  826. }
  827. if(GenerateCount != 0) LogMessage(0, $"一键生成文件夹成功,共 {GenerateCount}个");
  828. }
  829. private void SN1_KeyDown(object sender, KeyEventArgs e)
  830. {
  831. if (e.KeyCode != Keys.Enter) return;
  832. if (string.IsNullOrEmpty(SN1.Text)) return;
  833. SN2.Focus();
  834. SN2.SelectAll();
  835. }
  836. private void SN2_KeyDown(object sender, KeyEventArgs e)
  837. {
  838. if (e.KeyCode != Keys.Enter) return;
  839. if (string.IsNullOrEmpty(SN2.Text)) return;
  840. SN3.Focus();
  841. SN3.SelectAll();
  842. }
  843. private void SN3_KeyDown(object sender, KeyEventArgs e)
  844. {
  845. if (e.KeyCode != Keys.Enter) return;
  846. if (string.IsNullOrEmpty(SN3.Text)) return;
  847. SN4.Focus();
  848. SN4.SelectAll();
  849. }
  850. private void SN4_KeyDown(object sender, KeyEventArgs e)
  851. {
  852. if (e.KeyCode != Keys.Enter) return;
  853. if (string.IsNullOrEmpty(SN4.Text)) return;
  854. SN5.Focus();
  855. SN5.SelectAll();
  856. }
  857. private void SN5_KeyDown(object sender, KeyEventArgs e)
  858. {
  859. if (e.KeyCode != Keys.Enter) return;
  860. if (string.IsNullOrEmpty(SN5.Text)) return;
  861. SN6.Focus();
  862. SN6.SelectAll();
  863. }
  864. private void SN6_KeyDown(object sender, KeyEventArgs e)
  865. {
  866. if (e.KeyCode != Keys.Enter) return;
  867. if (string.IsNullOrEmpty(SN6.Text)) return;
  868. Generate.Focus();
  869. }
  870. public string CheckFileAccess(string filePath)
  871. {
  872. try
  873. {
  874. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  875. {
  876. return "OK";
  877. }
  878. }
  879. catch (IOException ex)
  880. {
  881. return "NG,文件被占用: " + ex.Message;
  882. }
  883. catch (UnauthorizedAccessException ex)
  884. {
  885. return "NG,权限不足,无法访问文件: " + ex.Message;
  886. }
  887. catch (Exception ex)
  888. {
  889. return "NG," + ex.Message;
  890. }
  891. }
  892. public string CheckFolderPermissions(string path)
  893. {
  894. try
  895. {
  896. DirectorySecurity security = Directory.GetAccessControl(path);
  897. AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
  898. WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
  899. foreach (FileSystemAccessRule rule in rules)
  900. {
  901. if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
  902. {
  903. Console.WriteLine($" {rule.IdentityReference.Value}");
  904. Console.WriteLine($"权限类型: {rule.AccessControlType}");
  905. Console.WriteLine($"具体权限: {rule.FileSystemRights}");
  906. Console.WriteLine($"是否继承: {rule.IsInherited}");
  907. }
  908. }
  909. return "OK";
  910. }
  911. catch (UnauthorizedAccessException ex)
  912. {
  913. return $"NG,无权限访问文件夹: {ex.Message}";
  914. }
  915. catch (DirectoryNotFoundException)
  916. {
  917. return "NG,文件夹不存在";
  918. }
  919. catch (Exception ex)
  920. {
  921. return "NG," + ex.Message;
  922. }
  923. }
  924. public class Log
  925. {
  926. public string SN { set; get; }
  927. public string Result { set; get; }
  928. public string TestTime { set; get; }
  929. public string Side { set; get; }
  930. public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
  931. }
  932. public class LogItem
  933. {
  934. public string Location { set; get; }
  935. public string ReelNo { set; get; }
  936. public string FirstType { set; get; }
  937. public string SceondType { set; get; }
  938. public string Name { set; get; }
  939. }
  940. }
  941. }