Make_ParseLog.cs 30 KB

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