using System; using System.Collections.Generic; using System.Net; using System.Text; using System.IO; using System.Windows.Forms; namespace Welling_Motor_Debug_Tool { public class ftp { 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; } /// /// 检查网络 /// /// bool 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; FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); ftpResponse.Close(); IsNetConnected = true; return true; } catch (Exception) { IsNetConnected = false; return false; } } /// /// 文件上传 /// /// 要上传文件全名 /// 服务器端地址(temp) /// public bool UploadFile(string sourceFullPath, string targetPath) { FtpWebRequest reqFTP = null; FileStream fs = null; Stream strm = null; FileInfo fileInf = new FileInfo(sourceFullPath); string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("\\") + 1); //远端存在该文件时,先删除 if (FileExist(targetPath, fileName)) { DeleteFile(targetPath + "/" + fileName); } Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + targetPath + "/" + Uri.EscapeDataString(fileName)); reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.Credentials = new NetworkCredential(userId, passWord); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.UsePassive = true; reqFTP.ContentLength = fileInf.Length; byte[] buff = new byte[2048]; int contentLen = 0; fs = fileInf.OpenRead(); try { strm = reqFTP.GetRequestStream(); while ((contentLen = fs.Read(buff, 0, buff.Length)) != 0) { strm.Write(buff, 0, contentLen); } fs.Close(); strm.Close(); return true; } catch (Exception ex) { fs.Close(); strm.Close(); //throw new Exception("上传文件失败,原因: " + ex.Message); return false; } } /// /// 文件下载 /// /// 文件本地存放路径 /// 远端文件路径 /// 文件名 /// bool public bool DownloadFile(string sourceFullPath, string targetFullPath) { FtpWebRequest ftpRequest = null; FileStream outputStream = null; FtpWebResponse response = null; Stream ftpStream = null; try { string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/") + 1); if (Directory.Exists(targetFullPath) == false) Directory.CreateDirectory(targetFullPath); outputStream = new FileStream(targetFullPath + "\\" + fileName, FileMode.Create); Uri uri = new Uri("ftp://" + serverIP + "/" + sourceFullPath); ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri); ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpRequest.UseBinary = true; ftpRequest.UsePassive = true; ftpRequest.Proxy = null; ftpRequest.Credentials = new NetworkCredential(userId, passWord); response = (FtpWebResponse)ftpRequest.GetResponse(); ftpStream = response.GetResponseStream(); int readCount = 0; byte[] buffer = new byte[2048]; while ((readCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, readCount); } outputStream.Close(); ftpStream.Close(); response.Close(); return true; } catch (Exception ex) { outputStream.Close(); ftpStream.Close(); response.Close(); //throw new Exception("下载文件失败,原因: " + ex.Message); return false; } } /// /// 删除文件 /// /// public void DeleteFile(string fileName) { try { Uri uri = new Uri("ftp://" + serverIP + "/" + fileName); FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.Credentials = new NetworkCredential(userId, passWord); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; reqFTP.UsePassive = false; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("文件删除失败!" + ex.Message); } } /// /// 删除文件夹 /// /// public void RemoveDirectory(string folderName) { try { Uri uri = new Uri("ftp://" + serverIP + "/" + folderName); FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.Credentials = new NetworkCredential(userId, passWord); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; reqFTP.UsePassive = false; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("文件夹删除失败!" + ex.Message); } } /// /// 获取当前目录下明细(包含文件和文件夹) /// /// 远端的地址 /// /// /// private string[] GetFileList(string ServerPath, string WRMethods) { StringBuilder result = null; FtpWebRequest ftp = null; WebResponse response = null; StreamReader reader = null; try { result = new StringBuilder(); Uri uri = new Uri("ftp://" + serverIP + "/" + ServerPath); ftp = (FtpWebRequest)FtpWebRequest.Create(uri); ftp.Credentials = new NetworkCredential(userId,passWord); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; ftp.UsePassive = true; response = ftp.GetResponse(); reader = new StreamReader(response.GetResponseStream(), 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(); response.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 bool FileExist(string rootDir, string fileName) { string[] fileList = GetFileNameList(rootDir); if (fileList.Length > 0) { foreach (string file in fileList) { if (file.Substring(file.LastIndexOf("/") + 1) == fileName) { return true; } } } return false; } /// /// 创建目录 /// /// public void MakeDir(string dirName) { FtpWebRequest reqFTP; try { Uri uri = new Uri("ftp://" + serverIP + "/" + dirName); reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.UsePassive = true; reqFTP.Credentials = new NetworkCredential(userId,passWord); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show("创建文件失败,原因: " + ex.Message); } } /// /// 重命名 /// /// /// public void ReName(string currentFilename, string newFilename) { FtpWebRequest reqFTP; try { Uri uri = new Uri("ftp://" + serverIP + "/" + currentFilename); reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; reqFTP.UseBinary = true; reqFTP.UsePassive = false; reqFTP.Credentials = new NetworkCredential(userId,passWord); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { throw new Exception("FtpHelper ReName Error --> " + ex.Message); } } /// /// 移动文件 /// /// /// public void MovieFile(string currentFilename, string newDirectory) { ReName(currentFilename, newDirectory); } } }