Make_ParseLog.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. string imageName = Path.GetFileName(file);
  361. SN = imageName.Split('_')[0].ToString();
  362. if (imageName.ToUpper().Contains("NG"))
  363. {
  364. if (UploadImageToFtp(file, SN))
  365. {
  366. dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
  367. 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");
  368. }
  369. }
  370. if(Array.IndexOf(txtFiles, file) == 1)
  371. {
  372. string parentPath = Path.GetDirectoryName(file);
  373. string changeName = Path.Combine(parentPath, SN);
  374. if (!Directory.Exists(changeName))
  375. {
  376. Directory.CreateDirectory(changeName);
  377. }
  378. File.Move(file, changeName);
  379. }
  380. }
  381. }
  382. }
  383. catch (Exception ex)
  384. {
  385. LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
  386. }
  387. }
  388. private bool InsertDb(List<Log> logs, string PathName, int fileNum)
  389. {
  390. try
  391. {
  392. StringBuilder sql = new StringBuilder();
  393. StringBuilder details = new StringBuilder();
  394. List<string> param = new List<string>() { };
  395. foreach (var item in logs)
  396. {
  397. //string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  398. // from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  399. // where ma_code='{ma_code.Text}' and mcd_stepcode='" + User.CurrentStepCode + "'";
  400. //dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  401. //BaseUtil.SetFormValue(Controls, dt);
  402. string outMsg = "";
  403. param.Add(ma_code.Text);
  404. param.Add(item.SN);
  405. param.Add(User.UserSourceCode);
  406. param.Add(item.Result.ToUpper());
  407. param.Add(item.TestTime);
  408. param.Add(item.Side);
  409. param.Add(equiType);
  410. details.Clear();
  411. foreach (LogItem LI in item.LogItemList)
  412. {
  413. details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
  414. }
  415. param.Add(details.ToString());
  416. param.Add(outMsg);
  417. string[] paramList = param.ToArray();
  418. dh.CallProcedure("cs_insert_testrejects", ref paramList);
  419. if(paramList[8].Substring(0, 2) == "OK")
  420. {
  421. LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
  422. }
  423. else
  424. {
  425. LogMessage(1, paramList[8]);
  426. }
  427. param.Clear();
  428. if (logs.IndexOf(item) == logs.Count - 1)
  429. {
  430. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
  431. return true;
  432. }
  433. /* if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, false, out omakeCode, out oMsid, out oErrorMessage))
  434. {
  435. if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "设备日志解析", "OK", User.UserCode, false, out oErrorMessage))
  436. {
  437. string sqlStr = $@"select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode,pr_detail,ma_qty - nvl(mcd_okqty, 0) remain_qty
  438. from make left join makecraftdetail on mcd_maid=ma_id left join product on pr_code = ma_prodcode
  439. where ma_code='" + omakeCode + "' and mcd_stepcode='" + User.CurrentStepCode + "'";
  440. dt = (DataTable)dh.ExecuteSql(sqlStr, "select");
  441. BaseUtil.SetFormValue(Controls, dt);
  442. //记录操作日志
  443. LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, ma_code.Text, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", item.SN, "");
  444. string outMsg = "";
  445. param.Add(item.SN);
  446. param.Add(omakeCode);
  447. param.Add(User.UserSourceCode);
  448. param.Add(item.Result);
  449. param.Add(outMsg);
  450. string[] paramList = param.ToArray();
  451. dh.CallProcedure("cs_insert_testdetail", ref paramList);
  452. LogMessage($"文件: {PathName},共{fileNum}条记录SN: {item.SN}解析已过站");
  453. param.Clear();
  454. if (logs.IndexOf(item) == logs.Count - 1)
  455. {
  456. return true;
  457. }
  458. }
  459. else
  460. {
  461. LogMessage($"处理过站NG:{oErrorMessage}");
  462. break;
  463. }
  464. }
  465. else
  466. {
  467. LogMessage($"过站核对NG:{oErrorMessage}");
  468. break;
  469. }*/
  470. }
  471. return false;
  472. }
  473. catch (Exception ex)
  474. {
  475. LogMessage(0, $"Error,处理解析写入: {ex.Message}");
  476. return false;
  477. }
  478. }
  479. private void ChangeWoFunc(object sender, EventArgs e)
  480. {
  481. try
  482. {
  483. sql.Clear();
  484. sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
  485. dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
  486. if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
  487. {
  488. ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
  489. return;
  490. }
  491. LogMessage(0, $"NG,自动识别更新工单");
  492. }
  493. catch (Exception ex)
  494. {
  495. LogMessage(0, $"Error,自动切换工单: {ex.Message}");
  496. }
  497. }
  498. private bool ConsoleLog(string Content, string PathName,string SN)
  499. {
  500. try
  501. {
  502. string sourcePaht = Path.GetDirectoryName(PathName);
  503. string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
  504. string newFolderName = "Logs";
  505. string newFolderPath = Path.Combine(sourcePaht, newFolderName);
  506. if (!Directory.Exists(newFolderPath))
  507. {
  508. Directory.CreateDirectory(newFolderPath);
  509. }
  510. string newFileName = "Log_" + Path.GetFileName(changeName);
  511. string newFilePath = Path.Combine(newFolderPath, newFileName);
  512. File.AppendAllText(newFilePath, Content + Environment.NewLine);
  513. return true;
  514. }
  515. catch (Exception ex)
  516. {
  517. MessageBox.Show(this.ParentForm, ex.Message, "警告");
  518. return false;
  519. }
  520. }
  521. private void LogMessage(int type, string message)
  522. {
  523. if (type == 0)
  524. {
  525. if (lstFiles.InvokeRequired)
  526. {
  527. lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  528. return;
  529. }
  530. lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  531. lstFiles.TopIndex = lstFiles.Items.Count - 1;
  532. }
  533. else
  534. {
  535. if (lstOk.InvokeRequired)
  536. {
  537. lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
  538. return;
  539. }
  540. lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  541. lstOk.TopIndex = lstOk.Items.Count - 1;
  542. }
  543. }
  544. private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
  545. {
  546. if (e.Index < 0) return;
  547. e.DrawBackground();
  548. string txt = lstFiles.Items[e.Index].ToString().ToUpper();
  549. Brush color = Brushes.Black;
  550. if (txt.Contains("NG"))
  551. {
  552. color = Brushes.Red;
  553. }
  554. else if (txt.Contains("ERROR"))
  555. {
  556. color = Brushes.Red;
  557. }
  558. else
  559. {
  560. color = Brushes.Green;
  561. }
  562. e.DrawFocusRectangle();
  563. e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
  564. }
  565. public bool UploadImageToFtp(string localFilePath, string Sn)
  566. {
  567. string ftpServer;
  568. //string ftpServer = "ftp://10.8.0.215:21/xray/";
  569. //string ftpServer = "ftp://192.168.1.5:21/xray/";
  570. ftpServer = equiType == "Xray" ? "ftp://10.8.0.215:21/xray/" : "ftp://10.8.0.215:21/ccd/";
  571. ftpServer = equiType == "Xray" ? "ftp://192.168.1.5:21/xray/" : "ftp://192.168.1.5:21/ccd/";
  572. string username = "vsftpd";
  573. string password = "vsftpd3ef41637hy";
  574. string currentDate = DateTime.Now.ToString("yyyyMMdd");
  575. string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{currentDate}";
  576. /*string ftpFullPath = $"{ftpServer.TrimEnd('/')}/{Sn}";*/
  577. string outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
  578. if (outResult.Substring(0, 2) == "NG")
  579. {
  580. LogMessage(0, outResult);
  581. return false;
  582. }
  583. string remoteFileName = Path.GetFileName(localFilePath);
  584. string uri = $"{ftpFullPath}/{remoteFileName}";
  585. try
  586. {
  587. var request = (FtpWebRequest)WebRequest.Create(uri);
  588. request.Method = WebRequestMethods.Ftp.UploadFile;
  589. request.Credentials = new NetworkCredential(username, password);
  590. request.UsePassive = true;
  591. request.UseBinary = true;
  592. request.KeepAlive = false;
  593. using (var fileStream = File.OpenRead(localFilePath))
  594. using (var requestStream = request.GetRequestStream())
  595. {
  596. byte[] buffer = new byte[4096];
  597. int bytesRead;
  598. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
  599. {
  600. requestStream.Write(buffer, 0, bytesRead);
  601. }
  602. }
  603. using (var response = (FtpWebResponse)request.GetResponse())
  604. {
  605. LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
  606. return true;
  607. }
  608. }
  609. catch (WebException ex)
  610. {
  611. if (ex.Response is FtpWebResponse response)
  612. {
  613. LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  614. }
  615. else
  616. {
  617. LogMessage(0, $"NG,Web异常: {ex.Message}");
  618. }
  619. return false;
  620. }
  621. catch (Exception ex)
  622. {
  623. LogMessage(0, $"NG,上传失败: {ex.Message}");
  624. return false;
  625. }
  626. }
  627. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  628. {
  629. try
  630. {
  631. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  632. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  633. request.Credentials = new NetworkCredential(username, password);
  634. request.UsePassive = true;
  635. request.UseBinary = true;
  636. request.KeepAlive = false;
  637. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  638. {
  639. response.Close();
  640. return "OK,目录创建成功: " + response.StatusDescription;
  641. }
  642. }
  643. catch (WebException ex)
  644. {
  645. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  646. {
  647. return "OK,目录已存在: " + response.StatusDescription;
  648. }
  649. else
  650. {
  651. return "NG,创建目录时发生错误: " + ex.Message;
  652. }
  653. }
  654. }
  655. public string CheckFileAccess(string filePath)
  656. {
  657. try
  658. {
  659. using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
  660. {
  661. return "OK";
  662. }
  663. }
  664. catch (IOException ex)
  665. {
  666. return "NG,文件被占用: " + ex.Message;
  667. }
  668. catch (UnauthorizedAccessException ex)
  669. {
  670. return "NG,权限不足,无法访问文件: " + ex.Message;
  671. }
  672. catch (Exception ex)
  673. {
  674. return "NG," + ex.Message;
  675. }
  676. }
  677. public string CheckFolderPermissions(string path)
  678. {
  679. try
  680. {
  681. DirectorySecurity security = Directory.GetAccessControl(path);
  682. AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
  683. WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
  684. foreach (FileSystemAccessRule rule in rules)
  685. {
  686. if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
  687. {
  688. Console.WriteLine($" {rule.IdentityReference.Value}");
  689. Console.WriteLine($"权限类型: {rule.AccessControlType}");
  690. Console.WriteLine($"具体权限: {rule.FileSystemRights}");
  691. Console.WriteLine($"是否继承: {rule.IsInherited}");
  692. }
  693. }
  694. return "OK";
  695. }
  696. catch (UnauthorizedAccessException ex)
  697. {
  698. return $"NG,无权限访问文件夹: {ex.Message}";
  699. }
  700. catch (DirectoryNotFoundException)
  701. {
  702. return "NG,文件夹不存在";
  703. }
  704. catch (Exception ex)
  705. {
  706. return "NG," + ex.Message;
  707. }
  708. }
  709. public class Log
  710. {
  711. public string SN { set; get; }
  712. public string Result { set; get; }
  713. public string TestTime { set; get; }
  714. public string Side { set; get; }
  715. public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
  716. }
  717. public class LogItem
  718. {
  719. public string Location { set; get; }
  720. public string ReelNo { set; get; }
  721. public string FirstType { set; get; }
  722. public string SceondType { set; get; }
  723. public string Name { set; get; }
  724. }
  725. }
  726. }