| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498 |
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml.Linq;
- namespace FtpSurveillance
- {
- public class FTPOperation
- {
- public static JArray fileStringArray2 = new JArray();
- /// <summary>
- /// 通过socket判断ftp是否通畅(异步socket连接,同步发送接收数据 )
- /// </summary>
- /// <returns></returns>
- public string CheckLinkFtp(string ftpip, string serverFTPName, string serverFTPPassword,string port)
- {
- 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();
- }
- /// <summary>
- /// 通过socket判断ftp是否通畅
- /// </summary>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 传递FTP返回的byte数组和长度,返回状态码(int)
- /// </summary>
- /// <param name="retByte"></param>
- /// <param name="retLen"></param>
- /// <returns></returns>
- 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;
- }
- }
- /// <summary>
- /// 判断路径是否存在
- /// 读取里面所有文件
- /// </summary>
- /// <param name="path"></param>
- public JArray Checkpath(string path,out string errmsg)
- {
- 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("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;
- }
- /// <summary>
- /// 上传
- /// </summary>
- /// <param name="filename"></param>
- /// 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<XElement> 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("/"));
- }
- /// <summary>
- /// 创建文件夹
- /// </summary>
- /// <param name="dirName"></param>
- 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;
- }
- /// <summary>
- /// 检查目录是否存在
- /// </summary>
- /// <param name="ftpPath">要检查的目录的上一级目录</param>
- /// <param name="dirName">要检查的目录名</param>
- /// <returns>存在返回true,否则false</returns>
- 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("<DIR>"))
- {
- int index = datas[i].IndexOf("<DIR>");
- 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();
- }
- }
- }
|