using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; using System.Xml.Linq; namespace FtpConnection { public class FtpOperationClass { public static JArray fileStringArray2 = new JArray(); 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; } } /// /// 判断路径是否存在 /// 读取里面所有文件 /// /// public JArray Checkpath(string path, out string errmsg) { //System.Diagnostics.Debugger.Launch(); errmsg = ""; fileStringArray2 = new JArray(); try { ///判断选中的是文件还是文件夹 if (File.Exists(path)) { //是文件 //System.IO.Path.GetExtension("c:\windows\test.txt")'获取扩展名 String fileName = System.IO.Path.GetFileName(path); //'获取文件名 JObject inputObj = new JObject(); inputObj.Add("key", (JToken)fileName); //string filepath = System.IO.Path.GetDirectoryName(path); //获取文件夹 inputObj.Add("pathName", ""); inputObj.Add("value", path); fileStringArray2.Add(inputObj); } else if (Directory.Exists(path)) { ///文件夹 if (string.IsNullOrEmpty(path)) { errmsg = "路径不存在!"; } else { DirectoryInfo dir = new DirectoryInfo(path); if (!dir.Exists) { errmsg = "路径不存在!"; } else { string pathService = path; dir = new DirectoryInfo(pathService); if (!dir.Exists) { errmsg = "路径不存在!"; } else { //读取里面所有文件 GetChildDicsNameService(dir, path, ""); } } } } } catch (Exception ex) { errmsg = "校验路径文档失败:" + ex.Message; return fileStringArray2; } if (fileStringArray2.Count > 0) { //生成文档 return fileStringArray2; } return fileStringArray2; } public static DirectoryInfo[] GetChildDicsNameService(DirectoryInfo dir, string path, string PathName) { FileInfo[] fileArray = dir.GetFiles(); DirectoryInfo[] childDirs = dir.GetDirectories(); FileInfo[] array = fileArray; foreach (FileInfo file in array) { string absolutePath = dir.FullName; string relativePath = absolutePath.Replace(path, ""); relativePath = relativePath.Replace("\\", "/"); if (relativePath != "") { relativePath += "/"; } string fileName = file.Name; relativePath = relativePath + fileName; JObject inputObj = new JObject(); inputObj.Add("key", (JToken)fileName); inputObj.Add("value", (JToken)relativePath); inputObj.Add("pathName", (JToken)PathName); fileStringArray2.Add(inputObj); } if (childDirs.Length != 0) { DirectoryInfo[] array2 = childDirs; foreach (DirectoryInfo dirChild in array2) { string urlName = PathName; if (urlName == "") { urlName = dirChild.Name; } else { urlName = urlName + "/" + dirChild.Name; } GetChildDicsNameService(dirChild, path, urlName); } } return childDirs; } /// /// 上传 /// /// /// filename 文件名 /// ftpRemotePath 到什么路径 /// ftpIP IP 地址 /// ftpUserName 用户名 /// ftpPassWord 密码 public string Upload(string filename, string ftpRemotePath, string ftpIP, string ftpUserName, string ftpPassWord) { string errorCode = "0"; string errorMessage = ""; FileInfo fileInf = new FileInfo(filename); //string uri = ftpPath; string ftpURI = "ftp://" + ftpIP + "/" + ftpRemotePath + "/"; string uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; string FtpCheckrtn = FtpCheckDirectoryExist(ftpRemotePath, "ftp://" + ftpIP, ftpUserName, ftpPassWord); //生成上传路径 JObject FtpCheckrtnObj = JObject.Parse(FtpCheckrtn); errorCode = FtpCheckrtnObj["errorCode"].ToString(); if (errorCode != "0") { return FtpCheckrtn; } reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassWord); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream fs = fileInf.OpenRead(); try { Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); } catch (Exception ex) { errorCode = "-1"; errorMessage = errorMessage + ";" + uri + ":" + ex.Message; } JObject returnobj = new JObject(); returnobj.Add("errorCode", errorCode); returnobj.Add("errorMessage", errorMessage); return returnobj.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 ExecuteAsAdmin(string fileName) { Process proc = new Process(); proc.StartInfo.FileName = fileName; proc.StartInfo.UseShellExecute = true; proc.StartInfo.Verb = "runas"; proc.Start(); } public static string FtpCheckDirectoryExist(string destFilePath, string ftpIP, string ftpUserID, string ftpPassword) { JObject jObject = new JObject(); string fullDir = FtpParseDirectory(destFilePath); string[] dirs = fullDir.Split('/'); string curDir = "/"; string errorCode = "0"; string errorMessage = ""; for (int i = 0; i < dirs.Length; i++) { string dir = dirs[i]; //如果是以/开始的路径,第一个为空 if (dir != null && dir.Length > 0) { try { string URI = ftpIP + curDir; string flagstring = DirectoryExist(URI, dir, ftpUserID, ftpPassword); JObject flagsobj = JObject.Parse(flagstring); if (flagsobj["errorCode"].ToString() == "-1") { //不存在就进行创建 string newFilePath = curDir + dir + "/"; MakeDir(newFilePath, ftpIP, ftpUserID, ftpPassword); } else if (flagsobj["errorCode"].ToString() != "0") { //错误 errorCode = flagsobj["errorCode"].ToString(); errorMessage = flagsobj["errorMessage"].ToString(); break; } curDir += dir + "/"; } catch (Exception ex) { errorCode = "-1"; errorMessage = ex.Message; jObject.Add("errorCode", errorCode); jObject.Add("errorMessage", errorMessage); return jObject.ToString(); } } } jObject.Add("errorCode", errorCode); jObject.Add("errorMessage", errorMessage); return jObject.ToString(); } public static string FtpParseDirectory(string destFilePath) { return destFilePath.Substring(0, destFilePath.LastIndexOf("/")); } /// /// 创建文件夹 /// /// public static Boolean MakeDir(string curDir, string ftpIP, string ftpUserID, string ftpPassword) { FtpWebRequest reqFTP; string errorCode = "0"; string errorMessage = ""; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpIP + curDir)); try { // dirName = name of the directory to create. reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.UseBinary = false; reqFTP.KeepAlive = false; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { errorCode = "-1"; errorMessage = errorMessage + ";" + ftpIP + "/" + curDir + ":" + ex.Message; reqFTP.Abort(); return false; } reqFTP.Abort(); return true; } /// /// 检查目录是否存在 /// /// 要检查的目录的上一级目录 /// 要检查的目录名 /// 存在返回true,否则false public static string DirectoryExist(string ftpPath, string dirName, string FTPName, string FTPPassword) { JObject jObject = new JObject(); string errorCode = "-1"; try { //实例化FTP连接 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath)); reqFTP.Credentials = new NetworkCredential(FTPName, FTPPassword); //指定FTP操作类型为创建目录 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //获取FTP服务器的响应 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default); StringBuilder str = new StringBuilder(); string line = sr.ReadLine(); while (line != null) { str.Append(line); str.Append("|"); line = sr.ReadLine(); } string[] datas = str.ToString().Split('|'); for (int i = 0; i < datas.Length; i++) { if (datas[i].Contains("")) { int index = datas[i].IndexOf(""); string name = datas[i].Substring(index + 5).Trim(); if (name == dirName) { errorCode = "0"; break; } } } sr.Close(); sr.Dispose(); response.Close(); } catch (Exception ex) { jObject.Add("errorCode", "-2"); jObject.Add("errorMessage", "MakeDir:" + ftpPath + "/" + dirName + ex.Message); return jObject.ToString(); } jObject.Add("errorCode", errorCode); jObject.Add("errorMessage", ""); return jObject.ToString(); } } }