using System; using System.Collections.Generic; using System.Net; using System.Text; using System.IO; namespace MOTINOVA_Motor_Factory_Set { public class ftp { #region string serverIP; string serverPort; string userId; string passWord; public bool IsNetConnected = false; public void FtpOption(string serverIP, string serverPort, string userId, string passWord) { this.serverIP = serverIP; this.serverPort = serverPort; this.userId = userId; this.passWord = passWord; } public bool CheckFtp() { try { Uri uri = new Uri(string.Format("ftp://{0}/{1}", serverIP, "/")); FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri); ftpRequest.Credentials = new NetworkCredential(userId, passWord); ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory; ftpRequest.Timeout = 2000; FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); IsNetConnected = true; return true; } catch (Exception ex) { IsNetConnected = false; return false; } } private FtpWebRequest OpenRequest(Uri uri, string ftpMethord) { try { FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri); ftpRequest.Credentials = new NetworkCredential(userId, passWord); ftpRequest.Method = ftpMethord; ftpRequest.UseBinary = true; return ftpRequest; } catch (Exception ex) { throw ex; } } private FtpWebResponse OpenResponse(Uri uri, string ftpMethord) { try { return this.OpenRequest(uri, ftpMethord).GetResponse() as FtpWebResponse; } catch { throw new Exception("登录到Ftp服务器失败!"); } } #endregion /// /// 下载(重命名) /// /// 下载文件全路径 /// 下载到本机全路径(包含文件名) /// public bool DownLoadReName(string sourceFullPath, string targetFullPath) { try { Uri uri = new Uri("ftp://" + serverIP + "/" + sourceFullPath); FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.DownloadFile); Stream responseStream = downloadResponse.GetResponseStream(); FileStream fileStream = File.Create(targetFullPath); byte[] buffer = new byte[1024]; int bytesRead = 0; while (true) { bytesRead = responseStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; fileStream.Write(buffer, 0, bytesRead); } fileStream.Close(); responseStream.Close(); return true; } catch { throw new Exception("获取下载文件失败!"); } } /// /// 下载(按原名直接) /// www.jbxue.com /// 下载文件的全路径 /// 下载到指定的地址(E:/) /// public bool DownLoadNotReName(string sourceFullPath, string targePath) { try { string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/")); if (!Directory.Exists(targePath))//不存在就创建文件夹 { Directory.CreateDirectory(targePath); } return DownLoadReName(sourceFullPath, targePath + fileName); } catch (Exception ex) { throw ex; } } /// /// 文件上传 /// /// 要上传文件的地址(G:/Ftp.txt) /// 服务器端地址(temp) /// public bool UploadFile(string sourceFullPath, string targetPath) { try { string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("\\") + 1); //检查路径 Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + targetPath + "/" + Uri.EscapeDataString(fileName)); FtpWebRequest request = this.OpenRequest(uri, WebRequestMethods.Ftp.UploadFile); Stream requestStream = request.GetRequestStream(); FileStream fileStream = new System.IO.FileStream(sourceFullPath, FileMode.Open); byte[] buffer = new byte[2048]; int bytesRead; while (true) { bytesRead = fileStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; requestStream.Write(buffer, 0, bytesRead); } requestStream.Close(); request.GetResponse(); fileStream.Close(); return true; } catch (Exception) { return false; } } /// /// 获取目录文件详细信息 /// /// 远端的地址 /// /// /// private string[] GetFileList(string ServerPath, string WRMethods) { StringBuilder result = new StringBuilder(); try { Uri uri = new Uri("ftp://" + serverIP + "/" + ServerPath); FtpWebResponse downloadResponse = OpenResponse(uri, WRMethods); Stream responseStream = downloadResponse.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.Default); string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } if (result.ToString() != "") { result.Remove(result.ToString().LastIndexOf("\n"), 1); } reader.Close(); downloadResponse.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { throw new Exception("获取文件列表失败,原因: " + ex.Message); } } /// /// 获得文件列表 /// /// /// /// public string[] GetFileNameList(string dirName) { string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails); List strList = new List(); if (drectory.Length > 0) { foreach (string str in drectory) { if (str.Trim().Length == 0) continue; //会有两种格式的详细信息返回 //一种包含 //一种第一个字符串是drwxerwxx这样的权限操作符号 //现在写代码包容两种格式的字符串 if (!str.Trim().Contains("")) { strList.Add(str.Substring(str.LastIndexOf(":") + 4).Trim()) ; } else { if (str.Trim().Substring(0, 1).ToUpper() != "D") { strList.Add(str.Substring(str.LastIndexOf(":") + 1).Trim()) ; } } } } return strList.ToArray(); } /// /// 获得文件明晰 /// /// /// public string[] GetFilesDetailList(string dirName) { return GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails); } /// /// 获取目录列表 /// /// 远端的地址 /// /// public string[] GetDirectoryList(string dirName) { string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails); List strList = new List(); if (drectory.Length > 0) { foreach (string str in drectory) { if (str.Trim().Length == 0) continue; //会有两种格式的详细信息返回 //一种包含 //一种第一个字符串是drwxerwxx这样的权限操作符号 //现在写代码包容两种格式的字符串 if (str.Trim().Contains("")) { strList.Add(str.Substring(39).Trim()); } else { if (str.Trim().Substring(0, 1).ToUpper() == "D") { strList.Add(str.Substring(55).Trim()); } } } } return strList.ToArray(); } /// /// 判断当前目录下指定的子目录是否存在 /// /// 指定的目录名 public bool DirectoryExist(string rootDir, string RemoteDirectoryName) { string[] dirList = GetDirectoryList(rootDir);//获取子目录 if (dirList.Length > 0) { foreach (string str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } } return false; } /// /// 创建目录 /// /// public void MakeDir(string dirName) { try { Uri uri = new Uri("ftp://" + serverIP + "/" + dirName); FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.MakeDirectory); downloadResponse.Close(); } catch (Exception ex) { throw new Exception("创建文件失败,原因: " + ex.Message); } } } }