using Google.Protobuf; using HandyControl.Data; using JiangsuEarthquake.Common; using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using OperationResult = JiangsuEarthquake.Common.OperationResult; using HandyControl.Tools.Extension; using System.Windows.Forms; using System.Collections.ObjectModel; namespace JiangsuEarthquake.Models.FTP { public class FTPConnectModel : NotifyBase { #region Define private string ip; /// /// IP /// public string IP { get { return ip; } set { ip = value; this.DoNotify(); } } private int port; /// /// 端口 /// public int Port { get { return port; } set { port = value; this.DoNotify(); } } private string username; /// /// 用户名 /// public string UserName { get { return username; } set { username = value; this.DoNotify(); } } private string password; /// /// 密码 /// public string PassWord { get { return password; } set { password = value; this.DoNotify(); } } public string ftpRemotePath; //FTP目标目录 public string Ipath; //目标文件存放路径 private string frpurl; public string ftpURI //得到的FTPUrL { get { return frpurl; } set { frpurl = value; this.DoNotify(); } } public string ftpUrls; //得到相对的Url #endregion /// /// FTP请求对象 /// FtpWebRequest request = null; /// /// FTP响应对象 /// FtpWebResponse response = null; /// /// 文件目录 /// List fileLists = new List(); /// /// 多个消息实体 /// List operationResults = new List(); /// /// 单个消息实体 /// OperationResult operationResult = new OperationResult(); #region FTP初始化 /// /// 获取FTP的URL /// /// /// /// /// /// /// public string getFtpHelper(string ftpServerIP, int ftpServerPort, string ftpRemotePath, string ftpUserID, string ftpPassword, string Ipath) { this.IP = ftpServerIP; this.ftpRemotePath = ftpRemotePath; this.port = ftpServerPort; this.Ipath = Ipath; this.UserName = ftpUserID; this.PassWord = ftpPassword; this.ftpUrls = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/"; this.ftpURI = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/" + (string.IsNullOrEmpty(ftpRemotePath) ? "" : ftpRemotePath); return ftpURI; } /// /// 建立FTP链接,返回响应对象 /// /// FTP地址 /// 操作命令 /// private FtpWebResponse Open(Uri uri, string ftpMethod) { request = (FtpWebRequest)FtpWebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(this.UserName, this.PassWord); return (FtpWebResponse)request.GetResponse(); } /// /// 建立FTP链接,返回请求对象 /// /// FTP地址 /// 操作命令 private FtpWebRequest OpenRequest(Uri uri, string ftpMethod) { request = (FtpWebRequest)WebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(this.UserName, this.PassWord); return request; } /// /// 建立FTP链接,返回请求对象 /// /// FTP地址 /// 操作命令 private FtpWebRequest FTPRequest(Uri uri, string ftpMethod) { request = (FtpWebRequest)WebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; request.Credentials = new NetworkCredential(UserName, PassWord); return request; } /// /// 建立FTP链接,返回响应对象 /// /// 请求的URL /// 请求的方法 /// private FtpWebResponse FTPResponse(Uri uri, string ftpMethod) { try { request = (FtpWebRequest)FtpWebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.Timeout = 1000; request.KeepAlive = false; //保持接,其他方法关闭 request.Credentials = new NetworkCredential(UserName, PassWord); return (FtpWebResponse)request.GetResponse(); } catch { return null; } } /// /// 析构函数关闭连接,如果不了解析构函数,可以去网上查找C#析构函数 /// ~FTPConnectModel() { if (response != null) { response.Close(); response = null; } if (request != null) { request.Abort(); request = null; } } #endregion #region 列出当前目录的所有一级子目录 /// /// 列出当前目录的所有一级子目录 /// public List ListDirectories() { try { var listAll = ListFilesAndDirectories(); var listFile = listAll.Where(m => m.IsDirectory == true).ToList(); return listFile; } catch { return null; } } /// /// 列出当前目录的所有文件 /// public List ListFiles() { try { var listAll = ListFilesAndDirectories(); var listFile = listAll.Where(m => m.IsDirectory == false).ToList(); return listFile; } catch { return null; } } #endregion #region 获取当前目录的一级子目录和文件信息 //public static Regex FtpListDirectoryDetailsRegex = new Regex(@".*(?(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s*(?[0-9]*)\s*(?([0-9]|:)*)\s*(?.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase); //public static Regex FtpListDirectoryDetailsRegexYear = new Regex(@"\b\d{4}\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// /// 获取当前目录一级字目录和文件信息 /// /// 是否只获取目录 /// public List ListFilesAndDirectories() { try { var fileList = new List(); response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails); if (response == null) return null; using (var stream = response.GetResponseStream()) { using (var sr = new StreamReader(stream)) { string line = null; int index = 1; while ((line = sr.ReadLine()) != null) { var parts = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries); string fmsgTime; if (IsAllDigits(parts[7])) fmsgTime = Convert.ToDateTime(parts[7] + parts[5] + parts[6]).ToString("yyyy/MM/dd"); else fmsgTime = Convert.ToDateTime(DateTime.Now.Year.ToString() + parts[5] + parts[6]).ToString("yyyy/MM/dd"); DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo(); dtFormat.ShortDatePattern = "yyyy/MM/dd"; var fileInfo = new FTPModel { Index = index++, FileName = parts[8], FileSize = parts[4] == "4096" ? "" : parts[4] + "Bytes", CreateTime = Convert.ToDateTime(fmsgTime, dtFormat), FilePath = ftpRemotePath + "/" + parts[8], IsDirectory = line.StartsWith('d') ? true : false }; fileList.Add(fileInfo); //MatchCollection matchYear = FtpListDirectoryDetailsRegexYear.Matches(line); //Match match = FtpListDirectoryDetailsRegex.Match(line); //string month = match.Groups["month"].Value; //string day = match.Groups["day"].Value; ////string yearTime = match.Groups["yearTime"].Value; //string fileName = match.Groups["fileName"].Value; //string size = matchYear[0].Value; //string year = ""; //foreach (Match ma in matchYear) //{ // if (int.Parse(ma.Value) >= 2000 && int.Parse(ma.Value) <= 2050) // year = ma.Value; //} //if (year == "") // year = DateTime.Now.Year.ToString(); //string fmsgTime = Convert.ToDateTime(year + month + day).ToString("yyyy/MM/dd"); //DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo(); //dtFormat.ShortDatePattern = "yyyy/MM/dd"; //FTPModel model = null; //if (size=="") //{ // model = new FTPModel() // { // CreateTime = Convert.ToDateTime(fmsgTime, dtFormat), // FileName = fileName, // FilePath = ftpRemotePath + "/" + fileName, // IsDirectory = true // }; //} //else //{ // model = new FTPModel() // { // CreateTime = Convert.ToDateTime(fmsgTime, dtFormat), // FileName = fileName, // FileSize= size, // FilePath = ftpRemotePath + "/" + fileName, // IsDirectory = false // }; //} //if (line.StartsWith('d')) //代表是文件夹 //{ // model.IsDirectory = true; //} ////else if (line.StartsWith('l')) ////{ //// //model.IsDirectory = null; ////} //else if (line.StartsWith('-') || line.StartsWith('l')) //{ // model.IsDirectory = false; //} //fileList.Add(model); } } } return fileList; } catch { return null; } } /// /// 判断字符串是否全是数字 /// /// /// public static bool IsAllDigits(string str) { return str.All(char.IsDigit); } /// /// 下载 /// /// 下载后的保存路径 /// 要下载的文件名 public void Download(string saveFilePath, string downloadFileName) { try { using (FileStream outputStream = new FileStream(saveFilePath + "\\" + downloadFileName, FileMode.Create)) { response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile); using (Stream ftpStream = response.GetResponseStream()) { long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } } } } catch { } } /// /// 文件上传 /// /// 本地文件路径 public void Upload(string localFilePath) { try { FileInfo fileInf = new FileInfo(localFilePath); request = OpenRequest(new Uri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile); request.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; using (var fs = fileInf.OpenRead()) { using (var strm = request.GetRequestStream()) { contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } } } } catch { } } /// /// 删除文件 /// /// 要删除的文件名 public void DeleteFile(string remoteFileName) { response = Open(new Uri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile); } /// /// 删除目录(包括下面所有子目录和子文件) /// /// 要删除的带路径目录名:如web/test /* * 例:删除test目录 FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password"); helper.RemoveDirectory("web/test"); */ public void RemoveDirectory(string remoteDirectoryName) { GotoDirectory(remoteDirectoryName, true); var listAll = ListFilesAndDirectories(); foreach (var m in listAll) { if (m.IsDirectory) RemoveDirectory(m.FilePath); else DeleteFile(m.FileName); } GotoDirectory(remoteDirectoryName, true); response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory); } /// /// 切换当前目录 /// /// true:绝对路径 false:相对路径 public void GotoDirectory(string DirectoryName, bool IsRoot) { if (IsRoot) ftpRemotePath = DirectoryName; else ftpRemotePath += "/" + DirectoryName; ftpURI = "ftp://" + IP + "/" + ftpRemotePath + "/"; } /// /// 判断当前目录下指定的一级子目录是否存在 /// /// 指定的目录名 public bool IsDirectoryExist(string remoteDirectoryName) { var listDir = ListDirectories(); if (listDir.Count(m => m.FileName == remoteDirectoryName) > 0) return true; return false; } /// /// 判断当前目录下指定的子文件是否存在 /// /// 远程文件名 public bool IsFileExist(string remoteFileName) { var listFile = ListFiles(); if (listFile.Count(m => m.FileName == remoteFileName) > 0) return true; return false; } #endregion } }