Make_ParseLog.cs 35 KB

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