Make_ParseLog.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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("C:\\Users\\MI\\Desktop");
  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. switch (Device.SelectedIndex)
  88. {
  89. case 0:
  90. currFileType = "Txt";
  91. equiType = "AOI";
  92. //ChangeWoTimer.Start();
  93. break;
  94. case 1:
  95. currFileType = "jpg";
  96. equiType = "Xray";
  97. //ChangeWoTimer.Stop();
  98. break;
  99. case 2:
  100. currFileType = "jpg";
  101. equiType = "CCD";
  102. //ChangeWoTimer.Stop();
  103. break;
  104. }
  105. if (string.IsNullOrEmpty(ma_code.Text))
  106. {
  107. Device.SelectedIndex = -1;
  108. txtPath.Text = "";
  109. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  110. return;
  111. }
  112. txtPath.Text = fileList[Device.SelectedIndex];
  113. txtPath.Focus();
  114. txtPath.SelectAll();
  115. ma_code.Enabled = true;
  116. Choose.Enabled = true;
  117. txtPath.Enabled = false;
  118. }
  119. private void Choose_Click(object sender, EventArgs e)
  120. {
  121. using (var dialog = new FolderBrowserDialog())
  122. {
  123. if (dialog.ShowDialog() == DialogResult.OK)
  124. {
  125. txtPath.Text = dialog.SelectedPath;
  126. txtPath.Enabled = false;
  127. Device.Enabled = false;
  128. watcher.EnableRaisingEvents = false;
  129. }
  130. }
  131. }
  132. private void claerBtn_Click(object sender, EventArgs e)
  133. {
  134. lstFiles.Items.Clear();
  135. }
  136. private void allParse_Click(object sender, EventArgs e)
  137. {
  138. if (Device.SelectedIndex == 0)
  139. {
  140. if (string.IsNullOrEmpty(ma_code.Text))
  141. {
  142. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  143. return;
  144. }
  145. }
  146. if (Device.SelectedIndex == -1)
  147. {
  148. Device.Focus();
  149. Device.SelectAll();
  150. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  151. return;
  152. }
  153. if (String.IsNullOrEmpty(txtPath.Text))
  154. {
  155. txtPath.Focus();
  156. txtPath.SelectAll();
  157. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  158. return;
  159. }
  160. string[] txtFiles;
  161. if (equiType == "Xray")
  162. {
  163. txtFiles = Directory.GetDirectories(txtPath.Text);
  164. }
  165. else
  166. {
  167. txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  168. }
  169. if (txtFiles.Length == 0)
  170. {
  171. LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
  172. return;
  173. }
  174. RefreshFileList();
  175. }
  176. private void onWatch_Click(object sender, EventArgs e)
  177. {
  178. if (Device.SelectedIndex == 0)
  179. {
  180. if (string.IsNullOrEmpty(ma_code.Text))
  181. {
  182. MessageBox.Show(this.ParentForm, "请选择工单", "提示");
  183. return;
  184. }
  185. }
  186. if (Device.SelectedIndex == -1)
  187. {
  188. Device.Focus();
  189. Device.SelectAll();
  190. MessageBox.Show(this.ParentForm, "请选择设备", "提示");
  191. return;
  192. }
  193. if (String.IsNullOrEmpty(txtPath.Text))
  194. {
  195. txtPath.Focus();
  196. txtPath.SelectAll();
  197. MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
  198. return;
  199. }
  200. try
  201. {
  202. watcher.Path = txtPath.Text;
  203. watcher.Filter = $"*.{currFileType}";
  204. if (onWatch.Text == "开启解析")
  205. {
  206. watcher.EnableRaisingEvents = true;
  207. onWatch.Text = "关闭解析";
  208. }
  209. else
  210. {
  211. watcher.EnableRaisingEvents = false;
  212. onWatch.Text = "开启解析";
  213. }
  214. }
  215. catch (Exception ex)
  216. {
  217. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  218. }
  219. }
  220. private void OnFileCreated(object sender, FileSystemEventArgs e)
  221. {
  222. RefreshFileList();
  223. }
  224. private void OnFileChanged(object sender, FileSystemEventArgs e)
  225. {
  226. if (e.ChangeType == WatcherChangeTypes.Changed)
  227. {
  228. RefreshFileList();
  229. }
  230. }
  231. private void RefreshFileList()
  232. {
  233. if (lstFiles.InvokeRequired)
  234. {
  235. lstFiles.Invoke(new Action(RefreshFileList));
  236. lstFiles.BeginInvoke(new Action(RefreshFileList));
  237. return;
  238. }
  239. try
  240. {
  241. if (!Directory.Exists(txtPath.Text))
  242. {
  243. LogMessage(0, $"目录不存在: {txtPath.Text}");
  244. return;
  245. }
  246. string[] txtFiles;
  247. if (equiType == "Xray")
  248. {
  249. txtFiles = Directory.GetDirectories(txtPath.Text);
  250. }
  251. else
  252. {
  253. txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
  254. }
  255. if (txtFiles.Length == 0)
  256. {
  257. return;
  258. }
  259. foreach (string file in txtFiles)
  260. {
  261. if (equiType == "Xray")
  262. {
  263. if (Path.GetFileName(file).Contains("Log_"))
  264. {
  265. continue;
  266. }
  267. if (!Directory.Exists(file))
  268. {
  269. LogMessage(0, $"文件夹不存在: {file}");
  270. }
  271. outFileMsg = CheckFolderPermissions(file);
  272. if (outFileMsg != "OK")
  273. {
  274. LogMessage(0, outFileMsg);
  275. continue;
  276. }
  277. }
  278. else
  279. {
  280. if (!File.Exists(file))
  281. {
  282. LogMessage(0, $"文件不存在: {file}");
  283. }
  284. outFileMsg = CheckFileAccess(file);
  285. if (outFileMsg != "OK")
  286. {
  287. LogMessage(0, outFileMsg);
  288. continue;
  289. }
  290. if (File.ReadAllText(file).Length == 0)
  291. {
  292. continue;
  293. }
  294. }
  295. if (equiType == "AOI")
  296. {
  297. using (StreamReader SR = new StreamReader(file, Encoding.GetEncoding("GBK")))
  298. {
  299. string Content = SR.ReadToEnd();
  300. SR.Close();
  301. SR.Dispose();
  302. List<Log> logArr = new List<Log>() { };
  303. string[] lines = Content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
  304. int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
  305. Log itemLog = new Log() { };
  306. foreach (var item in lines)
  307. {
  308. if (string.IsNullOrEmpty(item)) continue;
  309. if (Array.IndexOf(lines, item) == 1) itemLog.SN = item.Split(':')[1].ToString().Trim();
  310. if (Array.IndexOf(lines, item) == 2) itemLog.TestTime = item.Split(':')[1].Split('.')[0].ToString().Trim();
  311. if (Array.IndexOf(lines, item) == 3) itemLog.Result = item.Split(':')[1].ToString().Trim();
  312. if (Array.IndexOf(lines, item) == 4) itemLog.Side = item.Split(':')[1].ToString().Trim();
  313. if (item.IndexOf("元件位置") > -1)
  314. {
  315. LogItem list = new LogItem();
  316. int ind = Array.IndexOf(lines, item);
  317. list.Location = lines[ind].Split(':')[1].ToString().Trim();
  318. list.ReelNo = lines[ind + 1].Split(':')[1].ToString().Trim();
  319. list.FirstType = lines[ind + 2].Split(':')[1].ToString().Trim();
  320. list.SceondType = lines[ind + 3].Split(':')[1].ToString().Trim();
  321. list.Name = lines[ind + 4].Split(':')[1].ToString().Trim();
  322. itemLog.LogItemList.Add(list);
  323. }
  324. }
  325. logArr.Add(itemLog);
  326. if (logArr.Count == 0)
  327. {
  328. break;
  329. }
  330. if (InsertDb(logArr, file, fileNum))
  331. {
  332. if (ConsoleLog(Content, file, logArr[0].SN))
  333. {
  334. File.WriteAllText(file, string.Empty);
  335. File.Delete(file);
  336. }
  337. }
  338. }
  339. }
  340. else if (equiType == "Xray")
  341. {
  342. string[] floderFile = Directory.GetFiles(file, $"*.{currFileType}");
  343. foreach(string floderFileItem in floderFile)
  344. {
  345. SN = Path.GetFileName(floderFileItem).Split('-')[0];
  346. if (UploadImageToFtp(floderFileItem, SN))
  347. {
  348. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  349. VALUES ( steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text}','{User.UserSourceCode}', sysdate,'Xray', 'http://192.168.1.5:8088/ftp/xray/{DateTime.Now.ToString("yyyyMMdd")}/{Path.GetFileName(floderFileItem)}' )", "insert");
  350. if (Array.IndexOf(floderFile, floderFileItem) == floderFile.Length - 1)
  351. {
  352. string newFloderName = Path.GetDirectoryName(file);
  353. Directory.Move(file, Path.Combine(newFloderName, "Log_" + Path.GetFileName(file)));
  354. }
  355. }
  356. }
  357. }
  358. else if(equiType == "CCD")
  359. {
  360. if (txtFiles.Length != 2) break;
  361. foreach (var fileItem in txtFiles)
  362. {
  363. string imageName = Path.GetFileName(fileItem);
  364. SN = imageName.Split('_')[0].ToString();
  365. if (imageName.ToUpper().Contains("NG"))
  366. {
  367. if (UploadImageToFtp(fileItem, SN))
  368. {
  369. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  370. 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");
  371. }
  372. }
  373. string parentPath = Path.GetDirectoryName(file);
  374. string changeName = Path.Combine(parentPath, SN);
  375. if (!Directory.Exists(changeName))
  376. {
  377. Directory.CreateDirectory(changeName);
  378. }
  379. File.Move(file, changeName);
  380. }
  381. }
  382. }
  383. }
  384. catch (Exception ex)
  385. {
  386. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  387. }
  388. }
  389. private bool InsertDb(List<Log> logs, string PathName, int fileNum)
  390. {
  391. try
  392. {
  393. StringBuilder sql = new StringBuilder();
  394. StringBuilder details = new StringBuilder();
  395. List<string> param = new List<string>() { };
  396. foreach (var item in logs)
  397. {
  398. //string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  399. // from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  400. // where ma_code='{ma_code.Text}' and mcd_stepcode='" + User.CurrentStepCode + "'";
  401. //dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  402. //BaseUtil.SetFormValue(Controls, dt);
  403. string outMsg = "";
  404. param.Add(ma_code.Text);
  405. param.Add(item.SN);
  406. param.Add(User.UserSourceCode);
  407. param.Add(item.Result.ToUpper());
  408. param.Add(item.TestTime);
  409. param.Add(item.Side);
  410. param.Add(equiType);
  411. details.Clear();
  412. foreach (LogItem LI in item.LogItemList)
  413. {
  414. details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
  415. }
  416. param.Add(details.ToString());
  417. param.Add(outMsg);
  418. string[] paramList = param.ToArray();
  419. dh.CallProcedure("cs_insert_testrejects", ref paramList);
  420. if(paramList[8].Substring(0, 2) == "OK")
  421. {
  422. LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
  423. }
  424. else
  425. {
  426. LogMessage(1, paramList[8]);
  427. }
  428. param.Clear();
  429. if (logs.IndexOf(item) == logs.Count - 1)
  430. {
  431. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
  432. return true;
  433. }
  434. /* if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, false, out omakeCode, out oMsid, out oErrorMessage))
  435. {
  436. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "设备日志解析", "OK", User.UserCode, false, out oErrorMessage))
  437. {
  438. string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  439. from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  440. where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'";
  441. dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  442. BaseUtil.SetFormValue(Controls, dt);
  443. //记录操作日志
  444. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, "");
  445. string outMsg = "";
  446. param.Add(item.SN);
  447. param.Add(omakeCode);
  448. param.Add(User.UserSourceCode);
  449. param.Add(item.Result);
  450. param.Add(outMsg);
  451. string[] paramList = param.ToArray();
  452. dh.CallProcedure("cs_insert_testdetail", ref paramList);
  453. LogMessage($"文件: {PathName},共{fileNum}条记录SN: {item.SN}解析已过站");
  454. param.Clear();
  455. if (logs.IndexOf(item) == logs.Count - 1)
  456. {
  457. return true;
  458. }
  459. }
  460. else
  461. {
  462. LogMessage($"处理过站NG:{oErrorMessage}");
  463. break;
  464. }
  465. }
  466. else
  467. {
  468. LogMessage($"过站核对NG:{oErrorMessage}");
  469. break;
  470. }*/
  471. }
  472. return false;
  473. }
  474. catch (Exception ex)
  475. {
  476. LogMessage(0, $"Error,处理解析写入: {ex.Message}");
  477. return false;
  478. }
  479. }
  480. private void ChangeWoFunc(object sender, EventArgs e)
  481. {
  482. try
  483. {
  484. sql.Clear();
  485. sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
  486. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  487. if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
  488. {
  489. ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
  490. return;
  491. }
  492. LogMessage(0, $"NG,自动识别更新工单");
  493. }
  494. catch (Exception ex)
  495. {
  496. LogMessage(0, $"Error,自动切换工单: {ex.Message}");
  497. }
  498. }
  499. private bool ConsoleLog(string Content, string PathName,string SN)
  500. {
  501. try
  502. {
  503. string sourcePaht = Path.GetDirectoryName(PathName);
  504. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  505. string newFolderName = "Logs";
  506. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  507. if (!Directory.Exists(newFolderPath))
  508. {
  509. Directory.CreateDirectory(newFolderPath);
  510. }
  511. string newFileName = "Log_" + Path.GetFileName(changeName);
  512. string newFilePath = Path.Combine(newFolderPath, newFileName);
  513. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  514. return true;
  515. }
  516. catch (Exception ex)
  517. {
  518. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  519. return false;
  520. }
  521. }
  522. private void LogMessage(int type, string message)
  523. {
  524. if (type == 0)
  525. {
  526. if (lstFiles.InvokeRequired)
  527. {
  528. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  529. return;
  530. }
  531. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  532. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  533. }
  534. else
  535. {
  536. if (lstOk.InvokeRequired)
  537. {
  538. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  539. return;
  540. }
  541. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  542. lstOk.TopIndex = lstOk.Items.Count - 1;
  543. }
  544. }
  545. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  546. {
  547. if (e.Index < 0) return;
  548. e.DrawBackground();
  549. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  550. Brush color = Brushes.Black;
  551. if (txt.Contains("NG"))
  552. {
  553. color = Brushes.Red;
  554. }
  555. else if (txt.Contains("ERROR"))
  556. {
  557. color = Brushes.Red;
  558. }
  559. else
  560. {
  561. color = Brushes.Green;
  562. }
  563. e.DrawFocusRectangle();
  564. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  565. }
  566. public bool UploadImageToFtp(string localFilePath, string Sn)
  567. {
  568. string ftpServer;
  569. //string ftpServer = "ftp://10.8.0.215:21/xray/";
  570. //string ftpServer = "ftp://192.168.1.5:21/xray/";
  571. ftpServer = equiType == "Xray" ? "ftp://10.8.0.215:21/xray/" : "ftp://10.8.0.215:21/ccd/";
  572. ftpServer = equiType == "Xray" ? "ftp://192.168.1.5:21/xray/" : "ftp://192.168.1.5:21/ccd/";
  573. string username = "vsftpd";
  574. string password = "vsftpd3ef41637hy";
  575. string currentDate = DateTime.Now.ToString("yyyyMMdd");
  576. string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{currentDate}";
  577. /*string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{Sn}";*/
  578. string outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
  579. if (outResult.Substring(0, 2) == "NG")
  580. {
  581. LogMessage(0, outResult);
  582. return false;
  583. }
  584. string remoteFileName = Path.GetFileName(localFilePath);
  585. string uri = $"{ftpFullPath}/{remoteFileName}";
  586. try
  587. {
  588. var request = (FtpWebRequest)WebRequest.Create(uri);
  589. request.Method = WebRequestMethods.Ftp.UploadFile;
  590. request.Credentials = new NetworkCredential(username, password);
  591. request.UsePassive = true;
  592. request.UseBinary = true;
  593. request.KeepAlive = false;
  594. using (var fileStream = File.OpenRead(localFilePath))
  595. using (var requestStream = request.GetRequestStream())
  596. {
  597. byte[] buffer = new byte[4096];
  598. int bytesRead;
  599. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  600. {
  601. requestStream.Write(buffer, 0, bytesRead);
  602. }
  603. }
  604. using (var response = (FtpWebResponse)request.GetResponse())
  605. {
  606. LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
  607. return true;
  608. }
  609. }
  610. catch (WebException ex)
  611. {
  612. if (ex.Response is FtpWebResponse response)
  613. {
  614. LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  615. }
  616. else
  617. {
  618. LogMessage(0, $"NG,Web异常: {ex.Message}");
  619. }
  620. return false;
  621. }
  622. catch (Exception ex)
  623. {
  624. LogMessage(0, $"NG,上传失败: {ex.Message}");
  625. return false;
  626. }
  627. }
  628. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  629. {
  630. try
  631. {
  632. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  633. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  634. request.Credentials = new NetworkCredential(username, password);
  635. request.UsePassive = true;
  636. request.UseBinary = true;
  637. request.KeepAlive = false;
  638. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  639. {
  640. response.Close();
  641. return "OK,目录创建成功: " + response.StatusDescription;
  642. }
  643. }
  644. catch (WebException ex)
  645. {
  646. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  647. {
  648. return "OK,目录已存在: " + response.StatusDescription;
  649. }
  650. else
  651. {
  652. return "NG,创建目录时发生错误: " + ex.Message;
  653. }
  654. }
  655. }
  656. public string CheckFileAccess(string filePath)
  657. {
  658. try
  659. {
  660. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  661. {
  662. return "OK";
  663. }
  664. }
  665. catch (IOException ex)
  666. {
  667. return "NG,文件被占用: " + ex.Message;
  668. }
  669. catch (UnauthorizedAccessException ex)
  670. {
  671. return "NG,权限不足,无法访问文件: " + ex.Message;
  672. }
  673. catch (Exception ex)
  674. {
  675. return "NG," + ex.Message;
  676. }
  677. }
  678. public string CheckFolderPermissions(string path)
  679. {
  680. try
  681. {
  682. DirectorySecurity security = Directory.GetAccessControl(path);
  683. AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
  684. WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
  685. foreach (FileSystemAccessRule rule in rules)
  686. {
  687. if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
  688. {
  689. Console.WriteLine($" {rule.IdentityReference.Value}");
  690. Console.WriteLine($"权限类型: {rule.AccessControlType}");
  691. Console.WriteLine($"具体权限: {rule.FileSystemRights}");
  692. Console.WriteLine($"是否继承: {rule.IsInherited}");
  693. }
  694. }
  695. return "OK";
  696. }
  697. catch (UnauthorizedAccessException ex)
  698. {
  699. return $"NG,无权限访问文件夹: {ex.Message}";
  700. }
  701. catch (DirectoryNotFoundException)
  702. {
  703. return "NG,文件夹不存在";
  704. }
  705. catch (Exception ex)
  706. {
  707. return "NG," + ex.Message;
  708. }
  709. }
  710. public class Log
  711. {
  712. public string SN { set; get; }
  713. public string Result { set; get; }
  714. public string TestTime { set; get; }
  715. public string Side { set; get; }
  716. public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
  717. }
  718. public class LogItem
  719. {
  720. public string Location { set; get; }
  721. public string ReelNo { set; get; }
  722. public string FirstType { set; get; }
  723. public string SceondType { set; get; }
  724. public string Name { set; get; }
  725. }
  726. }
  727. }