| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039 |
- using DevExpress.Utils.CodedUISupport;
- using DevExpress.Xpo.Logger;
- using HslCommunication;
- using NPOI.POIFS.NIO;
- using NPOI.SS.Formula.Functions;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Security.AccessControl;
- using System.Security.Principal;
- using System.Text;
- using System.Web.Services.Description;
- using System.Web.UI.WebControls;
- using System.Windows.Forms;
- using UAS_MES_NEW.CustomControl.ButtonUtil;
- using UAS_MES_NEW.DataOperate;
- using UAS_MES_NEW.Entity;
- using UAS_MES_NEW.PublicMethod;
- namespace UAS_MES_NEW.Make
- {
- public partial class Make_ParseLog : Form
- {
- public Make_ParseLog()
- {
- InitializeComponent();
- }
- FileSystemWatcher watcher;
- LogStringBuilder sql = new LogStringBuilder();
- DataTable Dbfind;
- DataTable dt;
- DataHelper dh;
- string currFileType = "", equiType = "";
- string ccdTestRes = "OK"; //两面都OK为OK,否则为NG
- List<string> ccdNgFile = new List<string>();
- string SN, omakeCode, oMsid, oErrorMessage = "";
- List<string> fileList = new List<string>();
- Timer ChangeWoTimer;
- string outFileMsg;
- private void Make_ParseLog_Load(object sender, EventArgs e)
- {
- dh = SystemInf.dh;
- Choose.Enabled = false;
- fileList.Add("E:\\AOIMes\\Mes");
- fileList.Add("E:\\UAS");
- fileList.Add("");
- ChangeWoTimer = new Timer();
- ChangeWoTimer.Interval = 30000;
- ChangeWoTimer.Tick += ChangeWoFunc;
- watcher = new FileSystemWatcher();
- watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
- watcher.Created += OnFileCreated;
- watcher.Changed += OnFileChanged;
- /*watcher.Deleted += OnFileChanged;
- watcher.Renamed += OnFileChanged;*/
- //设置锁定工单
- LockMakeCode.GetMakeCodeCtl(ma_code);
- ma_code.SetLockCheckBox(LockMakeCode);
- //工单号放大镜配置
- ma_code.TableName = "make left join product on ma_prodcode=pr_code";
- ma_code.SelectField = "ma_code # 工单号,pr_code # 产品编号,pr_detail # 产品名称";
- ma_code.FormName = Name;
- ma_code.SetValueField = new string[] { "ma_code", "pr_code", "pr_detail" };
- ma_code.Condition = "ma_statuscode='STARTED'";
- ma_code.DbChange += Ma_code_DbChange;
- }
- private void Ma_code_DbChange(object sender, EventArgs e)
- {
- Dbfind = ma_code.ReturnData;
- BaseUtil.SetFormValue(this.Controls, Dbfind);
- //获取工单的其他信息
- sql.Clear();
- sql.Append("select ma_code,nvl(mcd_okqty,0) mcd_okqty,ma_prodcode as pr_code ,pr_detail,");
- sql.Append("pr_spec,ma_qty - nvl(mcd_inqty, 0) mcd_remainqty from make left join makecraftdetail on ");
- 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 + "'");
- dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
- if (dt.Rows.Count > 0)
- {
- BaseUtil.SetFormValue(this.Controls, dt);
- }
- }
- private void Device_SelectedIndexChanged(object sender, EventArgs e)
- {
- if (Device.SelectedIndex == -1) return;
- if(ChangeWoTimer.Enabled) ChangeWoTimer.Stop();
- onWatch.Enabled = true;
- FileBox.Visible = false;
- switch (Device.SelectedIndex)
- {
- case 0:
- currFileType = "Txt";
- equiType = "AOI";
- /*ChangeWoTimer.Start();
- ChangeWoFunc(null, null);*/
- break;
- case 1:
- currFileType = "bmp";
- equiType = "Xray";
- onWatch.Enabled = false;
- FileBox.Visible = true;
- break;
- case 2:
- currFileType = "jpg";
- equiType = "CCD";
- break;
- }
- txtPath.Text = fileList[Device.SelectedIndex];
- txtPath.Focus();
- txtPath.SelectAll();
- ma_code.Enabled = true;
- Choose.Enabled = true;
- txtPath.Enabled = false;
- }
- private void Choose_Click(object sender, EventArgs e)
- {
- using (var dialog = new FolderBrowserDialog())
- {
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- txtPath.Text = dialog.SelectedPath;
- txtPath.Enabled = false;
- Device.Enabled = false;
- watcher.EnableRaisingEvents = false;
- }
- }
- }
- private void claerBtn_Click(object sender, EventArgs e)
- {
- lstFiles.Items.Clear();
- }
- private void allParse_Click(object sender, EventArgs e)
- {
- if (String.IsNullOrEmpty(ma_code.Text))
- {
- ma_code.Focus();
- MessageBox.Show(this.ParentForm, "请选择归属工单", "提示");
- return;
- }
- if (Device.SelectedIndex == -1)
- {
- Device.Focus();
- Device.SelectAll();
- MessageBox.Show(this.ParentForm, "请选择设备", "提示");
- return;
- }
- if (String.IsNullOrEmpty(txtPath.Text))
- {
- txtPath.Focus();
- txtPath.SelectAll();
- MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
- return;
- }
- string[] txtFiles;
- if (equiType == "Xray")
- {
- txtFiles = Directory.GetDirectories(txtPath.Text);
- if (txtFiles.Length == 0)
- {
- LogMessage(0, $"当前路径{txtPath.Text},没有{equiType}设备输出的文件夹");
- return;
- }
- }
- else
- {
- txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
- if (txtFiles.Length == 0)
- {
- LogMessage(0, $"当前{txtPath.Text},没有{equiType}设备输出的{currFileType.ToLower()}文件");
- return;
- }
- }
- RefreshFileList();
- }
- private void onWatch_Click(object sender, EventArgs e)
- {
- if (String.IsNullOrEmpty(ma_code.Text))
- {
- ma_code.Focus();
- MessageBox.Show(this.ParentForm, "请选择归属工单", "提示");
- return;
- }
- if (Device.SelectedIndex == -1)
- {
- Device.Focus();
- Device.SelectAll();
- MessageBox.Show(this.ParentForm, "请选择设备", "提示");
- return;
- }
- if (String.IsNullOrEmpty(txtPath.Text))
- {
- txtPath.Focus();
- txtPath.SelectAll();
- MessageBox.Show(this.ParentForm, "请选择解析路径", "提示");
- return;
- }
- try
- {
- watcher.Path = txtPath.Text;
- watcher.Filter = $"*.{currFileType}";
- if (onWatch.Text == "开启解析")
- {
- watcher.EnableRaisingEvents = true;
- onWatch.Text = "关闭解析";
- }
- else
- {
- watcher.EnableRaisingEvents = false;
- onWatch.Text = "开启解析";
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(this.ParentForm, ex.Message, "警告");
- }
- }
- private void OnFileCreated(object sender, FileSystemEventArgs e)
- {
- RefreshFileList();
- }
- private void OnFileChanged(object sender, FileSystemEventArgs e)
- {
- if (e.ChangeType == WatcherChangeTypes.Changed)
- {
- RefreshFileList();
- }
- }
- private void RefreshFileList()
- {
- if (lstFiles.InvokeRequired)
- {
- lstFiles.Invoke(new Action(RefreshFileList));
- lstFiles.BeginInvoke(new Action(RefreshFileList));
- return;
- }
- try
- {
- if (!Directory.Exists(txtPath.Text))
- {
- LogMessage(0, $"目录不存在: {txtPath.Text}");
- return;
- }
- string[] txtFiles;
- if (equiType == "Xray")
- {
- txtFiles = Directory.GetDirectories(txtPath.Text);
- }
- else
- {
- txtFiles = Directory.GetFiles(txtPath.Text, $"*.{currFileType}");
- }
- if (txtFiles.Length == 0)
- {
- return;
- }
- foreach (string file in txtFiles)
- {
- if (equiType == "Xray")
- {
- if (Path.GetFileName(file).Contains("Log_")) continue;
- if (!Directory.Exists(file))
- {
- LogMessage(0, $"文件夹不存在: {file}");
- }
- outFileMsg = CheckFolderPermissions(file);
- if (outFileMsg != "OK")
- {
- if(!outFileMsg.Contains("文件被占用"))
- {
- LogMessage(0, outFileMsg);
- }
- continue;
- }
- }else if (equiType == "CCD")
- {
- outFileMsg = CheckFileAccess(file);
- if (outFileMsg != "OK")
- {
- //LogMessage(0, outFileMsg);
- //continue;
- }
- }
- else
- {
- if (!File.Exists(file))
- {
- LogMessage(0, $"文件不存在: {file}");
- }
- if (File.ReadAllText(file).Length == 0)
- {
- continue;
- }
- }
- if (equiType == "AOI")
- {
- using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
- using (StreamReader SR = new StreamReader(fileStream, Encoding.GetEncoding("GBK")))
- {
- string Content = SR.ReadToEnd();
- SR.Close();
- SR.Dispose();
- List<Log> logArr = new List<Log>() { };
- string[] lines = Content.Split(new string[] { "\r\n" }, StringSplitOptions.None);
- int fileNum = string.IsNullOrEmpty(lines[lines.Length - 1]) ? lines.Length - 1 : lines.Length;
- Log itemLog = new Log() { };
- foreach (var item in lines)
- {
- if (string.IsNullOrEmpty(item)) continue;
- if (Array.IndexOf(lines, item) == 1) itemLog.SN = item.Split(':')[1].ToString().Trim().Replace(";", ";");
- if (Array.IndexOf(lines, item) == 2) itemLog.TestTime = item.Split(':')[1].Split('.')[0].ToString().Trim();
- if (Array.IndexOf(lines, item) == 3) itemLog.Result = item.Split(':')[1].ToString().Trim();
- if (Array.IndexOf(lines, item) == 4) itemLog.Side = item.Split(':')[1].ToString().Trim();
- if (item.IndexOf("元件位置") > -1)
- {
- LogItem list = new LogItem();
- int ind = Array.IndexOf(lines, item);
- list.Location = lines[ind].Split(':')[1].ToString().Trim();
- list.ReelNo = lines[ind + 1].Split(':')[1].ToString().Trim();
- list.FirstType = lines[ind + 2].Split(':')[1].ToString().Trim();
- list.SceondType = lines[ind + 3].Split(':')[1].ToString().Trim();
- list.Name = lines[ind + 4].Split(':')[1].ToString().Trim();
- itemLog.LogItemList.Add(list);
- }
- }
- logArr.Add(itemLog);
- if (logArr.Count == 0)
- {
- break;
- }
- if (InsertDb(logArr, file, fileNum))
- {
- if (ConsoleLog(Content, file, logArr[0].SN))
- {
- File.WriteAllText(file, string.Empty);
- outFileMsg = CheckFileAccess(file);
- if (outFileMsg == "OK")
- {
- File.Delete(file);
- }
- }
- }
- }
- }
- else if (equiType == "Xray")
- {
- if (Path.GetFileName(file).Contains('_'))
- {
- SN = Path.GetFileName(file).Split('_')[1].Replace(";", ";");
- string[] floderFile = Directory.GetFiles(file, $"*.{currFileType}");
- foreach (string floderFileItem in floderFile)
- {
- if (UploadImageToFtp(floderFileItem, SN))
- {
- //if (!LogicHandler.CheckStepSNAndMacode("", User.UserSourceCode, SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
- //{
- // LogMessage(0, $"核对NG:{oErrorMessage}");
- //}
- dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
- VALUES ( steptestmain_seq.NEXTVAL,'{SN}','{ma_code.Text.Trim()}','{User.UserSourceCode}', sysdate,'Xray', 'http://192.168.1.5:8099/ftp/xray/{DateTime.Now.ToString("yyyyMMdd")}/{SN}/{Path.GetFileName(floderFileItem)}' )", "insert");
- if (Array.IndexOf(floderFile, floderFileItem) == floderFile.Length - 1)
- {
- string newFloderName = Path.GetDirectoryName(file);
- Directory.Move(file, Path.Combine(newFloderName, "Log_" + Path.GetFileName(file)));
- }
- }
- }
- }
- }
- else if(equiType == "CCD")
- {
- // 有2面CCD图片开始处理
- if (txtFiles.Length == 1) break;
- foreach (var fileItem in txtFiles)
- {
- string imageName = Path.GetFileName(fileItem);
- string iName = imageName.Split('_')[0];
- if (iName[0].ToString() == "A")
- {
- if (iName.ToUpper().Contains("NG"))
- {
- SN = iName.Substring(3);
- ccdTestRes = ccdTestRes == "NG" ? "NG" : "NG";
- ccdNgFile.Add(fileItem);
- }
- else
- {
- SN = iName.Substring(1);
- ccdTestRes = ccdTestRes == "NG" ? "NG" : "OK";
- }
- }else if(iName[0].ToString() == "B")
- {
- if (iName.ToUpper().Contains("NG"))
- {
- ccdTestRes = ccdTestRes == "NG" ? "NG" : "NG";
- ccdNgFile.Add(fileItem);
- }
- else
- {
- ccdTestRes = ccdTestRes == "NG" ? "NG" : "OK";
- }
- }
- }
- // 创建logs目录
- string parentPath = Path.GetDirectoryName(file);
- string newFolderPath = Path.Combine(parentPath, "Logs");
- if (!Directory.Exists(newFolderPath))
- {
- Directory.CreateDirectory(newFolderPath);
- }
- // logs目录下创建sn序列号目录
- string changeName = Path.Combine(newFolderPath, SN);
- if (!Directory.Exists(changeName))
- {
- Directory.CreateDirectory(changeName);
- }
- /*string result = Path.GetFileName(file).Split('_')[0];
- if (result.ToUpper().Contains("NG"))
- {
- if (UploadImageToFtp(file, SN))
- {
- dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
- 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");
- }
- }*/
- if (ccdTestRes == "NG") // 产品是否为NG
- {
- foreach (var fileItem in ccdNgFile)
- {
- if (UploadImageToFtp(file, SN)) // 上传NG面全部图片
- {
- dh.ExecuteSql($@"INSERT INTO steptestmain (sm_id, sm_sn,sm_makecode,sm_stepcode,sm_indate,sm_machinecode,sm_result)
- 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");
- }
- }
- }
- if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
- {
- if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, SN, "日志解析", "OK", User.UserCode, out oErrorMessage))
- {
- LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析成功", SN, "");
- LogMessage(1, $"序列号: {SN} 已过站解析");
- }
- else
- {
- LogMessage(0, $"序列号: {SN},处理过站NG:{oErrorMessage}");
- }
- }
- else
- {
- LogMessage(0, $"序列号: {SN},过站核对NG:{oErrorMessage}");
- }
- string targetFile = Path.Combine(changeName, Path.GetFileName(file));
- if (File.Exists(targetFile))
- {
- File.Delete(targetFile);
- }
- File.Move(file, targetFile);
- }
- }
- if (equiType == "CCD")
- {
- LogMessage(1, $"序列号: {SN} 图片已处理");
- }
- }
- catch (Exception ex)
- {
- LogMessage(0, $"Error: 解析文件列表失败: {ex.Message}");
- }
- }
- private bool InsertDb(List<Log> logs, string PathName, int fileNum)
- {
- try
- {
- StringBuilder sql = new StringBuilder();
- StringBuilder details = new StringBuilder();
- List<string> param = new List<string>() { };
- foreach (var item in logs)
- {
- dt = (DataTable)dh.ExecuteSql($"SELECT mp_id FROM makeprocess WHERE mp_sncode = '{item.SN}' AND mp_sourcecode = 'AOI'", "select");
- if (dt.Rows.Count > 0)
- {
- LogMessage(1, $"序列号:{item.SN}已经过站并记录测试信息");
- continue;
- }
- if (LogicHandler.CheckStepSNAndMacode(ma_code.Text, User.UserSourceCode, item.SN, User.UserCode, out omakeCode, out oMsid, out oErrorMessage))
- {
- if (LogicHandler.SetStepResult(omakeCode, User.UserSourceCode, item.SN, "日志解析", item.Result.ToUpper() == "PASS" ? "OK" :"NG", User.UserCode, out oErrorMessage))
- {
- string outMsg = "";
- param.Add(omakeCode);
- param.Add(item.SN);
- param.Add(User.UserSourceCode);
- param.Add(User.UserName);
- param.Add(User.CurrentStepCode);
- param.Add(item.Result.ToUpper());
- param.Add(item.TestTime);
- param.Add(item.Side);
- param.Add(equiType);
- details.Clear();
- foreach (LogItem LI in item.LogItemList)
- {
- details.Append($"{LI.Location}/{LI.ReelNo}/{LI.FirstType}/{LI.SceondType}/{LI.Name};");
- }
- param.Add(details.ToString());
- param.Add(outMsg);
- string[] paramList = param.ToArray();
- dh.CallProcedure("CS_INSERT_TESTDETAILS", ref paramList);
- if (paramList[10].Substring(0, 2) == "OK")
- {
- LogMessage(1, $"文件: {item.SN} 采集成功, 测试结果为{item.Result},共{item.LogItemList.Count}条信息");
- }
- else
- {
- LogMessage(1, paramList[8]);
- }
- param.Clear();
- if (logs.IndexOf(item) == logs.Count - 1)
- {
- LogicHandler.DoCommandLog(Tag.ToString(), User.UserCode, omakeCode, User.UserLineCode, User.UserSourceCode, "日志解析", "日志解析过站成功", item.SN, "");
- return true;
- }
- }
- else
- {
- LogMessage(0, $"处理过站NG:{oErrorMessage}");
- break;
- }
- }
- else
- {
- LogMessage(0, $"过站核对NG:{oErrorMessage}");
- break;
- }
- }
- return false;
- }
- catch (Exception ex)
- {
- LogMessage(0, $"Error,处理解析写入: {ex.Message}");
- return false;
- }
- }
- private void ChangeWoFunc(object sender, EventArgs e)
- {
- try
- {
- sql.Clear();
- sql.Append($"SELECT dl_macode FROM deviceline WHERE dl_linecode = '{User.UserLineCode}'");
- dt = (DataTable)dh.ExecuteSql(sql.GetString(), "select");
- if (dt.Rows.Count > 0 && !String.IsNullOrEmpty(dt.Rows[0]["dl_macode"].ToString()))
- {
- ma_code.Text = dt.Rows[0]["dl_macode"].ToString().Trim();
- return;
- }
- LogMessage(0, $"NG,自动识别更新工单");
- }
- catch (Exception ex)
- {
- LogMessage(0, $"Error,自动切换工单: {ex.Message}");
- }
- }
- private bool ConsoleLog(string Content, string PathName,string SN)
- {
- try
- {
- string sourcePaht = Path.GetDirectoryName(PathName);
- string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
- string newFolderName = "Logs";
- string newFolderPath = Path.Combine(sourcePaht, newFolderName);
- if (!Directory.Exists(newFolderPath))
- {
- Directory.CreateDirectory(newFolderPath);
- }
- string newFileName = "Log_" + Path.GetFileName(changeName);
- string newFilePath = Path.Combine(newFolderPath, newFileName);
- File.AppendAllText(newFilePath, Content + Environment.NewLine);
- return true;
- }
- catch (Exception ex)
- {
- MessageBox.Show(this.ParentForm, ex.Message, "警告");
- return false;
- }
- }
- private void LogMessage(int type, string message)
- {
- if (type == 0)
- {
- if (lstFiles.InvokeRequired)
- {
- lstFiles.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
- return;
- }
- lstFiles.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
- lstFiles.TopIndex = lstFiles.Items.Count - 1;
- }
- else
- {
- if (lstOk.InvokeRequired)
- {
- lstOk.Invoke(new Action<int, string>(LogMessage), new object[] { type, message });
- return;
- }
- lstOk.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
- lstOk.TopIndex = lstOk.Items.Count - 1;
- }
- }
- private void lstFiles_DrawItem(object sender, DrawItemEventArgs e)
- {
- if (e.Index < 0) return;
- e.DrawBackground();
- string txt = lstFiles.Items[e.Index].ToString().ToUpper();
- Brush color = Brushes.Black;
- if (txt.Contains("NG"))
- {
- color = Brushes.Red;
- }
- else if (txt.Contains("ERROR"))
- {
- color = Brushes.Red;
- }
- else
- {
- color = Brushes.Green;
- }
- e.DrawFocusRectangle();
- e.Graphics.DrawString(lstFiles.Items[e.Index].ToString(), e.Font, color, e.Bounds, StringFormat.GenericDefault);
- }
- public bool UploadImageToFtp(string localFilePath, string Sn)
- {
- string ftpServer;
- ftpServer = equiType == "Xray" ? "ftp://10.8.0.215:21/xray/" : "ftp://10.8.0.215:21/ccd/";
- ftpServer = equiType == "Xray" ? "ftp://192.168.1.5:21/xray/" : "ftp://192.168.1.5:21/ccd/";
- string username = "vsftpd";
- string password = "vsftpd3ef41637hy";
- string ftpTimePath = $"{ftpServer.TrimEnd('/')}/{DateTime.Now.ToString("yyyyMMdd")}";
- string outResult = CreateFtpDirectoryIfNotExists(ftpTimePath, username, password);
- if (outResult.Substring(0, 2) != "OK")
- {
- LogMessage(0, outResult);
- return false;
- }
- string ftpFullPath = $"{ftpTimePath}/{Sn}";
- outResult = CreateFtpDirectoryIfNotExists(ftpFullPath, username, password);
- if (outResult.Substring(0, 2) != "OK")
- {
- LogMessage(0, outResult);
- return false;
- }
- string remoteFileName = Path.GetFileName(localFilePath);
- string uri = $"{ftpFullPath}/{remoteFileName}";
- try
- {
- var request = (FtpWebRequest)WebRequest.Create(uri);
- request.Method = WebRequestMethods.Ftp.UploadFile;
- request.Credentials = new NetworkCredential(username, password);
- request.UsePassive = true;
- request.UseBinary = true;
- request.KeepAlive = false;
- using (var fileStream = File.OpenRead(localFilePath))
- using (var requestStream = request.GetRequestStream())
- {
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
- {
- requestStream.Write(buffer, 0, bytesRead);
- }
- }
- using (var response = (FtpWebResponse)request.GetResponse())
- {
- LogMessage(1, $"文件: {localFilePath}上传成功,状态{response.StatusDescription}");
- return true;
- }
- }
- catch (WebException ex)
- {
- if (ex.Response is FtpWebResponse response)
- {
- LogMessage(0, $"NG,FTP 错误码: {(int)response.StatusCode} - {response.StatusDescription}");
- }
- else
- {
- LogMessage(0, $"NG,Web异常: {ex.Message}");
- }
- return false;
- }
- catch (Exception ex)
- {
- LogMessage(0, $"NG,上传失败: {ex.Message}");
- return false;
- }
- }
- private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
- {
- try
- {
- FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
- request.Method = WebRequestMethods.Ftp.MakeDirectory;
- request.Credentials = new NetworkCredential(username, password);
- request.UsePassive = true;
- request.UseBinary = true;
- request.KeepAlive = false;
- using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
- {
- response.Close();
- return "OK,目录创建成功: " + response.StatusDescription;
- }
- }
- catch (WebException ex)
- {
- if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
- {
- return "OK,目录已存在: " + response.StatusDescription;
- }
- else
- {
- return "NG,创建目录时发生错误: " + ex.Message;
- }
- }
- }
- private void Delete_Click(object sender, EventArgs e)
- {
- if (!Directory.Exists(txtPath.Text))
- {
- LogMessage(0, $"删除路径不存在: {txtPath.Text}");
- return;
- }
- List<string> DeleteList = new List<string>() { };
- if (!string.IsNullOrEmpty(SN1.Text)) DeleteList.Add("1-1_" + SN1.Text);
- if (!string.IsNullOrEmpty(SN2.Text)) DeleteList.Add("1-2_" + SN2.Text);
- if (!string.IsNullOrEmpty(SN3.Text)) DeleteList.Add("1-3_" + SN3.Text);
- if (!string.IsNullOrEmpty(SN4.Text)) DeleteList.Add("2-1_" + SN4.Text);
- if (!string.IsNullOrEmpty(SN5.Text)) DeleteList.Add("2-2_" + SN5.Text);
- if (!string.IsNullOrEmpty(SN6.Text)) DeleteList.Add("2-3_" + SN6.Text);
- string DeletePath;
- int DeleteCount = 0;
- foreach (var item in DeleteList)
- {
- DeletePath = Path.Combine(txtPath.Text, item);
- if (DeletePath == txtPath.Text)
- {
- LogMessage(0, $"NG,路径{DeletePath}中,没有 {item} 文件夹");
- continue;
- }
- if (Directory.Exists(DeletePath))
- {
- try
- {
- Directory.Delete(DeletePath);
- }
- catch (IOException ex)
- {
- LogMessage(0, $"NG,文件夹{item}存有文件,{ex.Message}");
- continue;
- }
- catch (Exception ex)
- {
- LogMessage(0, $"NG,删除异常,{ex.Message}");
- continue;
- }
- DeleteCount++;
- if (SN1.Text == item) SN1.Text = "";
- if (SN2.Text == item) SN2.Text = "";
- if (SN3.Text == item) SN3.Text = "";
- if (SN4.Text == item) SN4.Text = "";
- if (SN5.Text == item) SN5.Text = "";
- if (SN6.Text == item) SN6.Text = "";
- }
- }
- if(DeleteCount != 0)
- {
- LogMessage(0, $"一键删除文件夹成功,共 {DeleteCount}个");
- return;
- }
- else
- {
- LogMessage(0, $"NG,请扫描SN序列号删除文件夹");
- }
- }
- private void Clear_Click(object sender, EventArgs e)
- {
- SN1.Text = "";
- SN2.Text = "";
- SN3.Text = "";
- SN4.Text = "";
- SN5.Text = "";
- SN6.Text = "";
- SN1.Focus();
- SN1.SelectAll();
- }
- private void Generate_Click(object sender, EventArgs e)
- {
- if (!Directory.Exists(txtPath.Text))
- {
- LogMessage(0, $"NG,生成路径不存在: {txtPath.Text}");
- return;
- }
- List<string> GenerateList = new List<string>() { };
- if (!string.IsNullOrEmpty(SN1.Text)) GenerateList.Add("1-1_" + SN1.Text);
- if (!string.IsNullOrEmpty(SN2.Text)) GenerateList.Add("1-2_" + SN2.Text);
- if (!string.IsNullOrEmpty(SN3.Text)) GenerateList.Add("1-3_" + SN3.Text);
- if (!string.IsNullOrEmpty(SN4.Text)) GenerateList.Add("2-1_" + SN4.Text);
- if (!string.IsNullOrEmpty(SN5.Text)) GenerateList.Add("2-2_" + SN5.Text);
- if (!string.IsNullOrEmpty(SN6.Text)) GenerateList.Add("2-3_" + SN6.Text);
- string GeneratePath;
- int GenerateCount = 0;
- foreach (var item in GenerateList)
- {
- GeneratePath = Path.Combine(txtPath.Text, item);
- if (GeneratePath == txtPath.Text)
- {
- LogMessage(0, $"NG,请扫描SN序列号创建文件夹");
- continue;
- }
- if (Directory.Exists(GeneratePath))
- {
- LogMessage(0, $"NG,路径{txtPath.Text}已有{item}文件夹");
- continue;
- }
- Directory.CreateDirectory(GeneratePath);
- GenerateCount++;
- }
- if(GenerateCount != 0) LogMessage(0, $"一键生成文件夹成功,共 {GenerateCount}个");
- }
- private void SN1_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode != Keys.Enter) return;
- if (string.IsNullOrEmpty(SN1.Text)) return;
- SN2.Focus();
- SN2.SelectAll();
- }
- private void SN2_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode != Keys.Enter) return;
- if (string.IsNullOrEmpty(SN2.Text)) return;
- SN3.Focus();
- SN3.SelectAll();
- }
- private void SN3_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode != Keys.Enter) return;
- if (string.IsNullOrEmpty(SN3.Text)) return;
- SN4.Focus();
- SN4.SelectAll();
- }
- private void SN4_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode != Keys.Enter) return;
- if (string.IsNullOrEmpty(SN4.Text)) return;
- SN5.Focus();
- SN5.SelectAll();
- }
- private void SN5_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode != Keys.Enter) return;
- if (string.IsNullOrEmpty(SN5.Text)) return;
- SN6.Focus();
- SN6.SelectAll();
- }
- private void SN6_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode != Keys.Enter) return;
- if (string.IsNullOrEmpty(SN6.Text)) return;
- Generate.Focus();
- }
- public string CheckFileAccess(string filePath)
- {
- try
- {
- using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
- {
- return "OK";
- }
- }
- catch (IOException ex)
- {
- return "NG,文件被占用: " + ex.Message;
- }
- catch (UnauthorizedAccessException ex)
- {
- return "NG,权限不足,无法访问文件: " + ex.Message;
- }
- catch (Exception ex)
- {
- return "NG," + ex.Message;
- }
- }
- public string CheckFolderPermissions(string path)
- {
- try
- {
- DirectorySecurity security = Directory.GetAccessControl(path);
- AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));
- WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
- foreach (FileSystemAccessRule rule in rules)
- {
- if (rule.IdentityReference.Value == currentUser.Name || currentUser.Groups.Contains(rule.IdentityReference))
- {
- Console.WriteLine($" {rule.IdentityReference.Value}");
- Console.WriteLine($"权限类型: {rule.AccessControlType}");
- Console.WriteLine($"具体权限: {rule.FileSystemRights}");
- Console.WriteLine($"是否继承: {rule.IsInherited}");
- }
- }
- return "OK";
- }
- catch (UnauthorizedAccessException ex)
- {
- return $"NG,无权限访问文件夹: {ex.Message}";
- }
- catch (DirectoryNotFoundException)
- {
- return "NG,文件夹不存在";
- }
- catch (Exception ex)
- {
- return "NG," + ex.Message;
- }
- }
- public class Log
- {
- public string SN { set; get; }
- public string Result { set; get; }
- public string TestTime { set; get; }
- public string Side { set; get; }
- public List<LogItem> LogItemList { set; get; } = new List<LogItem>();
- }
- public class LogItem
- {
- public string Location { set; get; }
- public string ReelNo { set; get; }
- public string FirstType { set; get; }
- public string SceondType { set; get; }
- public string Name { set; get; }
- }
- }
- }
|