using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Windows.Forms; using System.Xml.Linq; using Newtonsoft.Json; using System.Xml; using System.Text; using System.Net.Sockets; namespace prBrowser.Weblogic { public class FTPHelperNew { public string currentPath = ""; public string serverPath = ""; public string serverFTPName = "PRFTP"; public string serverFTPPassword = "pryk@2020"; public string ftpDefaultFolder = "browser"; public string hipIP = "http://10.204.72.74:8090"; public string hipURL = "/bdhealth/"; public string hipAuthorization = "Basic aGlwdXNlcjpob3NwSW5mb1BUIUAj"; public string versionNumberFileName = "UpdateList\\versionNumber.xml"; public string doUpdate(string inParams) { //System.Diagnostics.Debugger.Launch(); string logString = "开始调用更新程序0:------------------------------------------------------------------------------------------"; Log.LogInfo(logString, "doUpdate"); Log.LogInfo(inParams, "doUpdate"); string errorCode = "0"; string errorMessage = ""; JObject jObject = new JObject(); try { JObject inputEmpParamsObj = JObject.Parse(inParams); var paramsdata = inputEmpParamsObj["params"][0]; hipIP = paramsdata["hipIP"].ToString(); //hipIP hipURL = paramsdata["hipURL"].ToString(); //URL hipAuthorization = paramsdata["hipAuthorization"].ToString(); //hipAuthorization currentPath = AppDomain.CurrentDomain.BaseDirectory; serverPath = getXMLValue("prBrowser.exe.config", "UpdateUrl"); string UpdateList = CheckUpdate(inParams); if (UpdateList != "[]") { if ((serverPath == "") || (serverPath == null) || (serverPath == string.Empty)) { jObject.Add("errorCode", "-1"); jObject.Add("errorMessage", "ftp:地址为空"); Log.LogInfo(jObject.ToString(), "doUpdate"); return jObject.ToString(); } ///判断ftp地址通不通 string[] sArray = serverPath.Split(new string[1] { ":" }, StringSplitOptions.None); string ftpip = sArray[1].ToString().Replace("/", ""); string ftpport = sArray[2].ToString().Replace("/", ""); serverPath = "ftp://" + ftpip + ":" + ftpport + "/"; string checkinfo = CheckLinkFtp(ftpip, serverFTPName, serverFTPPassword, ftpport); JObject checkinfoobj = JObject.Parse(checkinfo); errorCode = checkinfoobj["errorCode"].ToString(); if (errorCode != "0") { errorMessage = checkinfoobj["errorMessage"].ToString(); jObject.Add("errorCode", errorCode); jObject.Add("errorMessage", errorMessage); Log.LogInfo(jObject.ToString(), "doUpdate"); return jObject.ToString(); } ///下载文件 JArray Updataarray = new JArray(); var UpdateListObj = JArray.Parse(UpdateList); foreach (var result in UpdateListObj) { string hipdllname = result["dllname"].ToString(); //文件名 string toaddress = result["toaddress"].ToString(); //to文件地址 string fromaddress = result["fromaddress"].ToString(); //from文件地址 string hipversionNumber = result["versionNumber"].ToString(); //版本号 //string rtn = DownLoad(下载到哪的路径", 下载的文件名, 从哪下载, serverFTPName, serverFTPPassword); //string uri = serverPath + ftpDefaultFolder + "/UpdateList/"; toaddress = ((!(toaddress == "")) ? (toaddress + "\\") : "\\"); fromaddress = ((!(fromaddress == "")) ? ("\\" + fromaddress + "\\") : "\\"); string toPath = currentPath + toaddress; //放到那个文件夹 string fromPath = serverPath + ftpDefaultFolder + fromaddress.Replace("\\", "/"); //从哪个文件夹下载 string rtn = DownLoad(toPath, hipdllname, fromPath, serverFTPName, serverFTPPassword); if (rtn == "0") { Updataarray.Add(result); errorMessage = errorMessage + ";" + hipdllname; } } //下载完成更新 更新列表xml if (Updataarray.ToString() != "[]") { SetUpdateList(Updataarray.ToString()); } MessageBox.Show("已更新到最新版"); } else { errorMessage = "已是最新版,无需更新!"; } } catch (Exception ex2) { errorCode = "-1"; errorMessage = ex2.Message; } jObject.Add("errorCode", errorCode); jObject.Add("errorMessage", errorMessage); Log.LogInfo(jObject.ToString(), "doUpdate"); logString = "结束调用更新程序:------------------------------------------------------------------------------------------"; Log.LogInfo(logString, "doUpdate"); return jObject.ToString(); } public string DownLoad(string filePath, string fileName, string ftpPath, string ftpUserName, string ftpPassWord) { try { if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } FileStream outputStream = new FileStream(filePath + fileName, FileMode.Create); FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath + fileName)); reqFTP.Method = "RETR"; reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassWord); reqFTP.UseBinary = true; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; for (int readCount = ftpStream.Read(buffer, 0, bufferSize); readCount > 0; readCount = ftpStream.Read(buffer, 0, bufferSize)) { outputStream.Write(buffer, 0, readCount); } ftpStream.Close(); outputStream.Close(); response.Close(); reqFTP = null; return "0"; } catch (Exception ex) { return ex.Message; } } public string CheckUpdate(string inParams) { int checkFlag = 0; string code = "0"; string message = ""; //再从hip获取文件版本 JObject jObject = new JObject(); HttpServices restClient = new HttpServices(); string hisResult = restClient.HISHTTPServices(inParams, hipIP, hipURL, hipAuthorization); //调用HIS回调 JObject hisResultobj = JObject.Parse(hisResult); code = hisResultobj["errorCode"].ToString(); message = hisResultobj["errorMessage"].ToString(); if (code != "0") // { return ""; } JArray array = new JArray(); var resultObj = hisResultobj["result"]; if (resultObj != null) { } else { return ""; } //先获取本地文件版本 if (System.IO.File.Exists(Path.GetFullPath(versionNumberFileName))) { IEnumerable enumerable = XDocument.Load(versionNumberFileName).Root.Element("list").Elements(); foreach (var result in resultObj) { string hipdllname = result["dllname"].ToString(); //文件名 string hipaddress = result["toaddress"].ToString(); //文件地址 hipaddress = hipaddress.Replace("\\", "/"); string hipversionNumber = result["versionNumber"].ToString(); //版本号 int flag = 1; //判断是否已更新 foreach (XElement item in enumerable) { string itemKey = item.Attribute("key").Value; string itemValue = item.Attribute("value").Value; string versionNumber = item.Attribute("versionNumber").Value; string serverItemValue = itemValue; if ((hipdllname == itemKey) && (itemValue == hipaddress) && (versionNumber == hipversionNumber)) { ///相同移除 flag = 0; } } //没在已更新列表里 if (flag == 1) { array.Add(result); } } } else { //没有更新列表就是全部更新 foreach (var result in resultObj) { array.Add(result); } } return array.ToString(); } private string getXMLValue(string path, string attr) { string xmlValue = ""; XDocument document = XDocument.Load(path); XElement root = document.Root; XElement settingEle = root.Element("appSettings"); IEnumerable enumerable = settingEle.Elements(); foreach (XElement item in enumerable) { if (item.Attribute("key").Value == attr) { xmlValue = item.Attribute("value").Value; } } return xmlValue; } public void SetUpdateList(string resultArr) { try { XmlDocument xmlDoc = new XmlDocument(); var UpdateListObj = JArray.Parse(resultArr); if (System.IO.File.Exists(Path.GetFullPath(versionNumberFileName))) { xmlDoc.Load(versionNumberFileName); XmlNode file = xmlDoc.SelectSingleNode("file"); XmlNodeList list = file.ChildNodes; foreach (XmlNode listobj in list) { foreach (var result in UpdateListObj) { string hipdllname = result["dllname"].ToString(); //文件名 string hipaddress = result["toaddress"].ToString(); //文件地址 hipaddress = hipaddress.Replace("\\", "/"); string hipversionNumber = result["versionNumber"].ToString(); //版本号 XmlElement add = xmlDoc.CreateElement("add"); add.SetAttribute("key", hipdllname); add.SetAttribute("value", hipaddress); add.SetAttribute("versionNumber", hipversionNumber); listobj.AppendChild(add); } file.AppendChild(listobj); } xmlDoc.Save(versionNumberFileName); } else { //没有更新列表就是全部更新 XmlElement xml = xmlDoc.CreateElement("", "file", ""); xmlDoc.AppendChild(xml); XmlNode file = xmlDoc.SelectSingleNode("file"); XmlElement list = xmlDoc.CreateElement("list"); foreach (var result in UpdateListObj) { string hipdllname = result["dllname"].ToString(); //文件名 string hipaddress = result["toaddress"].ToString(); //文件地址 hipaddress = hipaddress.Replace("\\", "/"); string hipversionNumber = result["versionNumber"].ToString(); //版本号 XmlElement add = xmlDoc.CreateElement("add"); add.SetAttribute("key", hipdllname); add.SetAttribute("value", hipaddress); add.SetAttribute("versionNumber", hipversionNumber); list.AppendChild(add); } file.AppendChild(list); xmlDoc.Save(versionNumberFileName); } } catch (Exception ex) { //MessageBox.Show("生成失败:" + ex.Message); } } public void ExecuteAsAdmin(string fileName) { Process proc = new Process(); proc.StartInfo.FileName = fileName; proc.StartInfo.UseShellExecute = true; proc.StartInfo.Verb = "runas"; proc.Start(); } public string CheckLinkFtp(string ftpip, string serverFTPName, string serverFTPPassword, string port) { //System.Diagnostics.Debugger.Launch(); string errorCode = "0"; string errorMessage = ""; bool checkflag = CheckFtp(ftpip, serverFTPName, serverFTPPassword, out errorMessage, Convert.ToInt32(port)); if (!checkflag) { errorCode = "-1"; } JObject returnobj = new JObject(); returnobj.Add("errorCode", errorCode); returnobj.Add("errorMessage", errorMessage); return returnobj.ToString(); } /// /// 通过socket判断ftp是否通畅 /// /// public static bool CheckFtp(string ip, string ftpuser, string ftppas, out string errmsg, int port = 21) { #region 输入数据检查 if (ftpuser.Trim().Length == 0) { errmsg = "FTP用户名不能为空,请检查设置!"; return false; } if (ftppas.Trim().Length == 0) { errmsg = "FTP密码不能为空,请检查设置!"; return false; } IPAddress address; try { address = IPAddress.Parse(ip); } catch { errmsg = string.Format("FTP服务器IP:{0}解析失败,请检查是否设置正确!", ip); return false; } #endregion bool ret = false; byte[] result = new byte[1024]; int pingStatus = 0, userStatus = 0, pasStatus = 0, exitStatus = 0; //连接返回,用户名返回,密码返回,退出返回 try { int receiveLength; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SendTimeout = 2000; socket.ReceiveTimeout = 2000;//超时设置成2000毫秒 try { socket.Connect(new IPEndPoint(address, port)); //以21端口进行连接 pingStatus = 200; } catch { pingStatus = -1; } if (pingStatus == 200) //状态码200 - TCP连接成功 { receiveLength = socket.Receive(result); pingStatus = getFtpReturnCode(result, receiveLength); //连接状态 if (pingStatus == 220)//状态码220 - FTP返回欢迎语 { socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "USER " + ftpuser, Environment.NewLine))); receiveLength = socket.Receive(result); userStatus = getFtpReturnCode(result, receiveLength); if (userStatus == 331)//状态码331 - 要求输入密码 { socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "PASS " + ftppas, Environment.NewLine))); receiveLength = socket.Receive(result); pasStatus = getFtpReturnCode(result, receiveLength); if (pasStatus == 230)//状态码230 - 登入因特网 { errmsg = string.Format("FTP:{0}@{1}登陆成功", ip, port); ret = true; socket.Send(Encoding.Default.GetBytes(string.Format("{0}{1}", "QUIT", Environment.NewLine))); //登出FTP receiveLength = socket.Receive(result); exitStatus = getFtpReturnCode(result, receiveLength); } else { // 状态码230的错误 errmsg = string.Format("FTP:{0}@{1}登陆失败,用户名或密码错误({2})", ip, port, pasStatus); } } else {// 状态码331的错误 errmsg = string.Format("使用用户名:‘{0}‘登陆FTP:{1}@{2}时发生错误({3}),请检查FTP是否正常配置!", ftpuser, ip, port, userStatus); } } else {// 状态码220的错误 errmsg = string.Format("FTP:{0}@{1}返回状态错误({2}),请检查FTP服务是否正常运行!", ip, port, pingStatus); } } else {// 状态码200的错误 errmsg = string.Format("无法连接FTP服务器:{0}@{1},请检查FTP服务是否启动!", ip, port); } socket.Close(); //关闭socket socket = null; } catch (Exception ex) { //连接出错 errmsg = string.Format("FTP:{0}@{1}连接出错:", ip, port) + ex.Message; ret = false; } return ret; } /// /// 传递FTP返回的byte数组和长度,返回状态码(int) /// /// /// /// private static int getFtpReturnCode(byte[] retByte, int retLen) { try { string str = Encoding.ASCII.GetString(retByte, 0, retLen).Trim(); return int.Parse(str.Substring(0, 3)); } catch { return -1; } } } }