using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FTP.Models { public class FTPConnectModel : NotifyBase { #region 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) { request = (FtpWebRequest)FtpWebRequest.Create(uri); request.Method = ftpMethod; request.UseBinary = true; request.KeepAlive = false; //保持接,其他方法关闭 request.Credentials = new NetworkCredential(UserName, PassWord); return (FtpWebResponse)request.GetResponse(); } /// /// 析构函数关闭连接,如果不了解析构函数,可以去网上查找C#析构函数 /// ~FTPConnectModel() { if (response != null) { response.Close(); response = null; } if (request != null) { request.Abort(); request = null; } } #endregion #region 列出当前目录的所有一级子目录 /// /// 列出当前目录的所有一级子目录 /// public List ListDirectories() { var listAll = ListFilesAndDirectories(); var listFile = listAll.Where(m => m.IsDirectory == true).ToList(); return listFile; } /// /// 列出当前目录的所有文件 /// public List ListFiles() { var listAll = ListFilesAndDirectories(); var listFile = listAll.Where(m => m.IsDirectory == false).ToList(); return listFile; } #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 List ListFilesAndDirectories() { var fileList = new List(); response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails); using (var stream = response.GetResponseStream()) { using (var sr = new StreamReader(stream)) { string line = null; while ((line = sr.ReadLine()) != null) { Match match = FtpListDirectoryDetailsRegex.Match(line); //string[] a = line.Split(' '); 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 fmsgTime = Convert.ToDateTime(DateTime.Now.ToString("yy") + month + day).ToString("yyyy-MM-dd") + " " + yearTime; Console.WriteLine(line); var model = new FTPModel() { CreateTime = Convert.ToDateTime(fmsgTime), FileName = fileName, FilePath = ftpRemotePath + "/" + fileName, IsDirectory = true }; 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; } /// /// 下载 /// /// 下载后的保存路径 /// 要下载的文件名 public void Download(string saveFilePath, string downloadFileName) { 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); } } } } /// /// 文件上传 /// /// 本地文件路径 public void Upload(string localFilePath) { 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); } } } } /// /// 删除文件 /// /// 要删除的文件名 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 } }