using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using System.Windows.Forms; using System.Xml; namespace FileWatcher { class BaseUtil { public static void CreateXml(string iSN, string iTestResult) { //创建XML文档 FileStream fcaches = new FileStream(iSN + ".xml", FileMode.OpenOrCreate, FileAccess.ReadWrite); fcaches.Close(); FileInfo info = new FileInfo(iSN + ".xml"); if (info.Length == 0) { XmlDocument doc = new XmlDocument(); //创建类型声明节点 XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", ""); doc.AppendChild(node); //创建根节点 XmlElement xeRoot = doc.CreateElement("cacheInfo"); doc.AppendChild(xeRoot); doc.Save(iSN + ".xml"); } } public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate) { dgv.AutoGenerateColumns = false; dgv.DataSource = dt; if (operate.Length > 0) { if (dgv.Columns[operate[0].Name] != null) { dgv.Columns.Remove(dgv.Columns[operate[0].Name]); } dgv.Columns.Add(operate[0]); } ////纯英文的列不予展示 //Regex regEnglish = new Regex("^[A-z]+$"); //foreach (DataGridViewColumn dgvc in dgv.Columns) //{ // if (regEnglish.IsMatch(dgvc.HeaderText)) // { // dgvc.Visible = false; // } //} } public static string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary dic, out string fp_path, out string fp_id) { fp_id = ""; fp_path = ""; try { ServicePointManager.DefaultConnectionLimit = 50; string boundary = DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1); request.Method = "POST"; request.Timeout = 10 * 10000; request.ContentType = "multipart/form-data; boundary=" + boundary; Stream rs = request.GetRequestStream(); var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n"; if (dic != null) { foreach (string key in dic.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, dic[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } } string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n"; { rs.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath)); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } } var cr = Encoding.UTF8.GetBytes("\r\n"); rs.Write(cr, 0, cr.Length); } rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); var response = request.GetResponse() as HttpWebResponse; StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string Content = newReader.ReadToEnd(); Dictionary dic1 = new Dictionary(); List> dic2 = null; dic1 = BaseUtil.ToDictionary(Content); dic2 = dic1["data"] as List>; if (dic2[0]["filepath"] != null) { fp_id = dic2[0]["filepath"].ToString(); fp_path = dic2[0]["path"].ToString(); } if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine(fp_id); return fp_id; } } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace); } return ""; } public static Dictionary ToDictionary(string JsonData) { object Data = null; Dictionary Dic = new Dictionary(); if (JsonData.StartsWith("[")) { //如果目标直接就为数组类型,则将会直接输出一个Key为List的List>集合 //使用示例List> ListDic = (List>)Dic["List"]; List> List = new List>(); MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组 foreach (Match ListItem in ListMatch) { List.Add(ToDictionary(ListItem.ToString()));//递归调用 } Data = List; Dic.Add("List", Data); } else { MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值 foreach (Match item in Match) { try { if (item.Groups[2].ToString().StartsWith("[")) { //如果目标是数组,将会输出一个Key为当前Json的List>集合 //使用示例List> ListDic = (List>)Dic["Json中的Key"]; List> List = new List>(); MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组 foreach (Match ListItem in ListMatch) { List.Add(ToDictionary(ListItem.ToString()));//递归调用 } Data = List; } else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入 Dic.Add(item.Groups[1].ToString(), Data); } catch { } } } return Dic; } public static Dictionary ToDictionary(string JsonData, string Type) { //实例化JavaScriptSerializer类的新实例 JavaScriptSerializer jss = new JavaScriptSerializer(); try { //将指定的 JSON 字符串转换为 Dictionary 类型的对象 return jss.Deserialize>(JsonData); } catch (Exception ex) { throw new Exception(ex.Message); } } public static object GetCacheData(string ParamName) { try { object returnData = null; //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, settings); doc.Load(reader); //先得到根节点 XmlNode rootNode = doc.SelectSingleNode("cacheInfo"); //再由根节点去找制定的节点 XmlNodeList nodeList = rootNode.ChildNodes; foreach (XmlNode node in nodeList) { //找到了这个节点名字 if (node.Name == ParamName) { //返回节点的内容 switch (((XmlElement)node).GetAttribute("Type")) { case "System.String": returnData = node.InnerText; break; case "System.Int32": returnData = int.Parse(node.InnerText); break; case "System.Boolean": returnData = node.InnerText == "True" ? true : false; break; default: break; } break; } } //关闭reader reader.Close(); if (returnData == null) return ""; else return returnData; } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace); return ""; } } public static void SetCacheData(string ParamName, object Value) { try { //根据地址读取xml文件 XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = new XmlReaderSettings(); //忽略文档里面的注释 settings.IgnoreComments = true; XmlReader reader = XmlReader.Create(AutoAnalysisXml.CachePath, settings); doc.Load(reader); //先得到根节点 XmlNode rootNode = doc.SelectSingleNode("cacheInfo"); //再由根节点去找制定的节点 XmlNodeList nodeList = rootNode.ChildNodes; bool flag = false; foreach (XmlNode node in nodeList) { //找到了这个节点名字 if (node.Name == ParamName) { //就直接赋值 node.InnerText = Value.ToString(); flag = true; } } //如果没有该节点,就创建节点保存结果 if (!flag) { //创建节点 XmlElement newNode = doc.CreateElement(ParamName); XmlAttribute attr = doc.CreateAttribute("Type"); attr.InnerText = Value.GetType().ToString(); newNode.InnerText = Value.ToString(); newNode.SetAttributeNode(attr); //讲新建的节点挂到根节点上 rootNode.AppendChild(newNode); } //关闭Reader reader.Close(); doc.Save(AutoAnalysisXml.CachePath); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); } } //播放音频文件 public static void PlaySound(string FileName) { //要加载COM组件:Microsoft speech object Library if (!System.IO.File.Exists(FileName)) { return; } //SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass(); //SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass(); //spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true); //SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream; //pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename); //spFs.Close(); } public static void GetWriteInfo(string FilePath, out Dictionary Dic) { Dic = new Dictionary(); string txt = ""; StreamReader sr = new StreamReader(FilePath); while (!sr.EndOfStream) { string str = sr.ReadLine(); txt += str + "\n"; } sr.Close(); sr.Dispose(); Dic.Add("atd_sncode", FilePath.Substring(FilePath.LastIndexOf("\\") + 1).Replace(".txt", "")); Dic.Add("atd_software", Regex.Match(txt, "Program Name,\\S+").Value.Replace("Program Name,", "")); Dic.Add("atd_pot", Regex.Match(txt, "Board Segment,\\S+").Value.Replace("Board Segment,", "")); Dic.Add("atd_size", Regex.Match(txt, "Baord Size \\(L x W\\) \\[mm\\],\\S+").Value.Replace("Baord Size (L x W) [mm],", "")); Dic.Add("atd_pot1set", Regex.Match(txt, "Pot-1 Set Temp. \\[deg],\\S+").Value.Replace("Pot-1 Set Temp. [deg],", "")); Dic.Add("atd_pot2set", Regex.Match(txt, "Pot-2 Set Temp. \\[deg],\\S+").Value.Replace("Pot-2 Set Temp. [deg],", "")); Dic.Add("atd_pot1avgtemp", Regex.Match(txt, "Pot-1 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-1 Avg. Temp. [deg],", "")); Dic.Add("atd_pot2avgtemp", Regex.Match(txt, "Pot-2 Avg. Temp. \\[deg],\\S+").Value.Replace("Pot-2 Avg. Temp. [deg],", "")); Dic.Add("atd_boardtime", Regex.Match(txt, "Machine Duration \\[s],\\S+").Value.Replace("Machine Duration [s],", "")); //开始时间 MatchCollection starttime = Regex.Matches(txt, "Start TimeStamp,\\S+ \\S+"); for (int i = 0; i < starttime.Count; i++) { switch (i) { case 0: Dic.Add("atd_boardstarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; case 1: Dic.Add("atd_flstarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; case 2: Dic.Add("atd_phstarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; case 3: Dic.Add("atd_sostarttime", starttime[i].Value.Replace("Start TimeStamp,", "")); break; default: break; } } MatchCollection endtime = Regex.Matches(txt, "End TimeStamp,\\S+ \\S+"); for (int i = 0; i < starttime.Count; i++) { switch (i) { case 0: Dic.Add("atd_boardendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; case 1: Dic.Add("atd_flendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; case 2: Dic.Add("atd_phendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; case 3: Dic.Add("atd_soendtime", endtime[i].Value.Replace("End TimeStamp,", "")); break; default: break; } } MatchCollection duration = Regex.Matches(txt, "Total Zone Duration \\[s],\\S+"); for (int i = 0; i < starttime.Count; i++) { switch (i) { case 0: Dic.Add("atd_fltime", duration[i].Value.Replace("Total Zone Duration [s],", "")); break; case 1: Dic.Add("atd_phtime", duration[i].Value.Replace("Total Zone Duration [s],", "")); break; case 2: Dic.Add("atd_sotime", duration[i].Value.Replace("Total Zone Duration [s],", "")); break; default: break; } } } } }