using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Windows.Forms; using System.Configuration; using System.Data; namespace Lskj.TxtFileRead { public class FtpHelper { static string ftpServerIP; static string ftpRemotePath; static string ftpUserID; static string ftpPassword; static string ftpURI; /// /// 连接FTP /// /// FTP连接地址 /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录 /// 用户名 /// 密码 public FtpHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) { ftpServerIP = FtpServerIP; ftpRemotePath = FtpRemotePath; ftpUserID = FtpUserID; ftpPassword = FtpPassword; ftpURI = @"ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } /// /// 从ftp服务器上获取文件并将内容全部转换成string返回 /// /// /// /// public string GetFileStr(string fileName, string dir) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpURI); reqFTP.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。 reqFTP.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); StreamReader reader = new StreamReader(ftpStream); string fileStr = reader.ReadToEnd(); reader.Close(); ftpStream.Close(); response.Close(); return fileStr; } catch (Exception ex) { MessageBox.Show("获取ftp文件并读取内容失败:" + ex.Message); return null; } } /// /// 下载 /// /// /// public void Download(string filePath, string fileName) { try { FileStream outputStream = new FileStream(@filePath + "\\" + fileName, FileMode.Create); FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 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); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 删除文件 /// /// public bool fileDelete(string ftpfileName) { bool success = false; FtpWebRequest ftpWebRequest = null; FtpWebResponse ftpWebResponse = null; Stream ftpResponseStream = null; StreamReader streamReader = null; try { string uri = ftpURI + ftpfileName; ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); ftpWebRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftpWebRequest.KeepAlive = false; ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile; ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); long size = ftpWebResponse.ContentLength; ftpResponseStream = ftpWebResponse.GetResponseStream(); streamReader = new StreamReader(ftpResponseStream); string result = String.Empty; result = streamReader.ReadToEnd(); success = true; } catch (Exception) { success = false; } finally { if (streamReader != null) { streamReader.Close(); } if (ftpResponseStream != null) { ftpResponseStream.Close(); } if (ftpWebResponse != null) { ftpWebResponse.Close(); } } return success; } //获取ftp上面的文件和文件夹 public string[] GetFileList() { string[] downloadFiles; StringBuilder result = new StringBuilder(); FtpWebRequest request; try { request = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); request.UseBinary = true; request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);//设置用户名和密码 request.Method = WebRequestMethods.Ftp.ListDirectory; request.UseBinary = true; request.UsePassive = false; //选择主动还是被动模式 , 这句要加上的。 request.KeepAlive = false;//一定要设置此属性,否则一次性下载多个文件的时候,会出现异常。 WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { MessageBox.Show("获取ftp上面的文件和文件夹:" + ex.Message); downloadFiles = null; return downloadFiles; } } public List GetAllList() { List list = new List(); FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(ftpURI)); req.Credentials = new NetworkCredential(ftpUserID, ftpPassword); req.Method = WebRequestMethods.Ftp.ListDirectory; req.UseBinary = true; req.UsePassive = true; try { using (FtpWebResponse res = (FtpWebResponse)req.GetResponse()) { using (StreamReader sr = new StreamReader(res.GetResponseStream())) { string s; while ((s = sr.ReadLine()) != null) { list.Add(s); } } } } catch (Exception ex) { throw (ex); } return list; } /// /// 获取当前目录下明细(包含文件和文件夹) /// public string[] GetFilesDetailList() { try { StringBuilder result = new StringBuilder(); FtpWebRequest ftp; ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = ftp.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); line = reader.ReadLine(); line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } 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 long GetFileSize(string filename) { FtpWebRequest reqFTP; long fileSize = 0; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { } return fileSize; } /// /// 创建文件夹 /// public void MakeDir(string dirName) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName)); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { } } /// /// 删除文件 /// public void Delete(string fileName) { try { FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; reqFTP.KeepAlive = 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 Upload(string filename) { FileInfo fileInf = new FileInfo(filename); FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.KeepAlive = false; 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) { throw new Exception(ex.Message); } } #region 从FTP服务器下载文件,指定本地路径和本地文件名 /// /// 从FTP服务器下载文件,指定本地路径和本地文件名 /// /// 远程文件名 /// 保存本地的文件名(包含路径) /// 是否启用身份验证(false:表示允许用户匿名下载) /// 报告进度的处理(第一个参数:总大小,第二个参数:当前进度) /// 是否下载成功 public bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action updateProgress = null) { FtpWebRequest reqFTP, ftpsize; Stream ftpStream = null; FtpWebResponse response = null; FileStream outputStream = null; try { outputStream = new FileStream(localFileName, FileMode.Create); Uri uri = new Uri(@"ftp://" + ftpServerIP + "/" + remoteFileName); ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri); ftpsize.UseBinary = true; reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.UseBinary = true; reqFTP.KeepAlive = false; if (ifCredential)//使用用户身份认证 { ftpsize.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); } ftpsize.Method = WebRequestMethods.Ftp.GetFileSize; FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse(); long totalBytes = re.ContentLength; re.Close(); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; response = (FtpWebResponse)reqFTP.GetResponse(); ftpStream = response.GetResponseStream(); //更新进度 if (updateProgress != null) { updateProgress((int)totalBytes, 0);//更新进度条 } long totalDownloadedByte = 0; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { totalDownloadedByte = readCount + totalDownloadedByte; outputStream.Write(buffer, 0, readCount); //更新进度 if (updateProgress != null) { updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条 } readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); return true; } catch (Exception ex) { MessageBox.Show("下载文件出现;" + ex.Message); return false; throw; } finally { if (ftpStream != null) { ftpStream.Close(); } if (outputStream != null) { outputStream.Close(); } if (response != null) { response.Close(); } } } /// /// 从FTP服务器下载文件,指定本地路径和本地文件名(支持断点下载) /// /// 远程文件名 /// 保存本地的文件名(包含路径) /// 是否启用身份验证(false:表示允许用户匿名下载) /// 已下载文件流大小 /// 报告进度的处理(第一个参数:总大小,第二个参数:当前进度) /// 是否下载成功 public static bool FtpBrokenDownload(string remoteFileName, string localFileName, bool ifCredential, long size, Action updateProgress = null) { FtpWebRequest reqFTP, ftpsize; Stream ftpStream = null; FtpWebResponse response = null; FileStream outputStream = null; try { outputStream = new FileStream(localFileName, FileMode.Append); Uri uri = new Uri(@"ftp://" + ftpServerIP + "/" + remoteFileName); ftpsize = (FtpWebRequest)FtpWebRequest.Create(uri); ftpsize.UseBinary = true; ftpsize.ContentOffset = size; reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri); reqFTP.UseBinary = true; reqFTP.KeepAlive = false; reqFTP.ContentOffset = size; if (ifCredential)//使用用户身份认证 { ftpsize.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); } ftpsize.Method = WebRequestMethods.Ftp.GetFileSize; FtpWebResponse re = (FtpWebResponse)ftpsize.GetResponse(); long totalBytes = re.ContentLength; re.Close(); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; response = (FtpWebResponse)reqFTP.GetResponse(); ftpStream = response.GetResponseStream(); //更新进度 if (updateProgress != null) { updateProgress((int)totalBytes, 0);//更新进度条 } long totalDownloadedByte = 0; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { totalDownloadedByte = readCount + totalDownloadedByte; outputStream.Write(buffer, 0, readCount); //更新进度 if (updateProgress != null) { updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条 } readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); return true; } catch (Exception ex) { MessageBox.Show("下载文件出现;" + ex.Message); return false; throw; } finally { if (ftpStream != null) { ftpStream.Close(); } if (outputStream != null) { outputStream.Close(); } if (response != null) { response.Close(); } } } /// /// 从FTP服务器下载文件,指定本地路径和本地文件名 /// /// 远程文件名 /// 保存本地的文件名(包含路径) /// 是否启用身份验证(false:表示允许用户匿名下载) /// 报告进度的处理(第一个参数:总大小,第二个参数:当前进度) /// 是否断点下载:true 会在localFileName 找是否存在已经下载的文件,并计算文件流大小 /// 是否下载成功 public bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, bool brokenOpen, Action updateProgress = null) { if (brokenOpen) { try { long size = 0; if (File.Exists(localFileName)) { using (FileStream outputStream = new FileStream(localFileName, FileMode.Open)) { size = outputStream.Length; } } return FtpBrokenDownload(remoteFileName, localFileName, ifCredential, size, updateProgress); } catch { throw; } } else { return FtpDownload(remoteFileName, localFileName, ifCredential, updateProgress); } } #endregion /// /// 获取本地某个文件夹下的文件 /// public string[] GetFiles(DirectoryInfo directory, string pattern) { StringBuilder sb = new StringBuilder(); if (directory.Exists || pattern.Trim() != string.Empty) { foreach (FileInfo info in directory.GetFiles(pattern)) { sb.AppendLine(info.FullName.ToString()); } foreach (DirectoryInfo info in directory.GetDirectories()) { GetFiles(info, pattern); } } sb.Remove(sb.ToString().LastIndexOf("\n"), 1); return sb.ToString().Split('\n'); } /// /// 接删除指定目录下的所有文件及文件夹(保留目录) /// public static void DeleteDir(string file) { try { //去除文件夹和子文件的只读属性 //去除文件夹的只读属性 System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file); fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory; //去除文件的只读属性 System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal); //判断文件夹是否还存在 if (Directory.Exists(file)) { foreach (string f in Directory.GetFileSystemEntries(file)) { if (File.Exists(f)) { //如果有子文件删除文件 File.Delete(f); Console.WriteLine(f); } else { //循环递归删除子文件夹 DeleteDir(f); } } //删除空文件夹 //Directory.Delete(file); Console.WriteLine(file); } } catch (Exception ex) // 异常处理 { Console.WriteLine(ex.Message.ToString());// 异常信息 } } } }