一些参考案例下面是一些常用的ftp操作文件的方法
案列1
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Windows.Forms; using System.Globalization; namespace FtpTest1 { public class FtpWeb { string ftpServerIP; string ftpRemotePath; string ftpUserID; string ftpPassword; string ftpURI; /// <summary> /// 连接FTP /// </summary> /// <param name="FtpServerIP">FTP连接地址</param> /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> /// <param name="FtpUserID">用户名</param> /// <param name="FtpPassword">密码</param> public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) { ftpServerIP = FtpServerIP; ftpRemotePath = FtpRemotePath; ftpUserID = FtpUserID; ftpPassword = FtpPassword; ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } /// <summary> /// 上传 /// </summary> /// <param name="filename"></param> public void Upload(string filename) { FileInfo fileInf = new FileInfo(filename); string uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message); } } /// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public void Download(string filePath, string fileName) { FtpWebRequest reqFTP; try { FileStream outputStream = new FileStream(filePath + "//" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message); } } /// <summary> /// 删除文件 /// </summary> /// <param name="fileName"></param> public void Delete(string fileName) { try { string uri = ftpURI + fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName); } } /// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> /// <returns></returns> public string[] GetFilesDetailList() { string[] downloadFiles; 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) { downloadFiles = null; Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message); return downloadFiles; } } /// <summary> /// 获取FTP文件列表包括文件夹 /// </summary> /// <returns></returns> private string[] GetAllList(string url,string userid,string password) { List<string> list = new List<string>(); FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url)); req.Credentials = new NetworkCredential(userid, password); 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.ToArray(); } /// <summary> /// 获取当前目录下文件列表 不包括文件夹 /// </summary> /// <returns></returns> public string[] GetFileList(string url,string userid,string password) { StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url)); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(userid, password); reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); while (line != null) { if (line.IndexOf("<DIR>")==-1) { result.Append(Regex.Match(line, @"[/S]+ [/S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]); result.Append("/n"); } line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('/n'), 1); reader.Close(); response.Close(); } catch (Exception ex) { throw (ex); } return result.ToString().Split('/n'); } /// <summary> /// 判断当前目录下指定的子目录是否存在 /// </summary> /// <param name="RemoteDirectoryName">指定的目录名</param> public bool DirectoryExist(string RemoteDirectoryName) { string[] dirList = GetDirectoryList(); foreach (string str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } return false; } /// <summary> /// 判断当前目录下指定的文件是否存在 /// </summary> /// <param name="RemoteFileName">远程文件名</param> public bool FileExist(string RemoteFileName) { string[] fileList = GetFileList("*.*"); foreach (string str in fileList) { if (str.Trim() == RemoteFileName.Trim()) { return true; } } return false; } /// <summary> /// 创建文件夹 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { FtpWebRequest reqFTP; try { // dirName = name of the directory to create. 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message); } } /// <summary> /// 获取指定文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message); } return fileSize; } /// <summary> /// 改名 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void ReName(string currentFilename, string newFilename) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename)); reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; 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) { Insert_Standard_ErrorLog.Insert("FtpWeb", "ReName Error --> " + ex.Message); } } /// <summary> /// 移动文件 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void MovieFile(string currentFilename, string newDirectory) { ReName(currentFilename, newDirectory); } /// <summary> /// 切换当前目录 /// </summary> /// <param name="DirectoryName"></param> /// <param name="IsRoot">true 绝对路径 false 相对路径</param> public void GotoDirectory(string DirectoryName, bool IsRoot) { if (IsRoot) { ftpRemotePath = DirectoryName; } else { ftpRemotePath += DirectoryName + "/"; } ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } }
案列2
1、 public class Helper { private string requestUriString = string.Empty; private string userName = string.Empty; private string password = string.Empty; private FtpWebRequest request; private FtpWebResponse response; public Helper() { } /// <summary> /// 构造函数 /// </summary> /// <param name="RequestUriString">登陆IP</param> /// <param name="UserName">用户名</param> /// <param name="Password">密码</param> public Helper(string RequestUriString, string UserName, string Password) { this.requestUriString = "ftp://" + RequestUriString + "/"; this.userName = UserName; this.password = Password; } /// <summary> /// 创建FtpWebRequest /// </summary> /// <param name="uriString">FTP路径</param> /// <param name="method">FTP方法</param> private void OpenRequest(string uriString, string method) { try { this.request = WebRequest.Create(new Uri(this.requestUriString + uriString)) as FtpWebRequest; this.request.Credentials = new NetworkCredential(userName, password); this.request.UseBinary = true; this.request.Method = method; } catch { } } /// <summary> /// 返回FtpWebResponse /// </summary> /// <param name="uriString">FTP路径</param> /// <param name="method">FTP方法</param> private void OpenResponse(string uriString, string method) { try { this.OpenRequest(uriString, method); this.response = this.request.GetResponse() as FtpWebResponse; } catch { } } /// <summary> /// 创建目录 /// </summary> /// <param name="directoryPath">要创建的目录名称</param> public void MakeDirectory(string directoryPath) { this.OpenResponse(directoryPath, WebRequestMethods.Ftp.MakeDirectory); } /// <summary> /// 删除目录 /// </summary> /// <param name="directoryPath">要删除的目录名称</param> public void RemoveDirectory(string directoryPath) { this.OpenResponse(directoryPath, WebRequestMethods.Ftp.RemoveDirectory); } /// <summary> /// 重命名文件 /// </summary> /// <param name="originalFileName">原文件名</param> /// <param name="newFileName">新文件名</param> public void Rename(string originalFileName, string newFileName) { this.OpenResponse(originalFileName, WebRequestMethods.Ftp.Rename); this.request.RenameTo = newFileName; this.response = this.request.GetResponse() as FtpWebResponse; } /// <summary> /// 上传文件到服务器 /// </summary> /// <param name="localFullPath">要上传的本地文件全路径</param> public void UploadFile(string localFullPath) { this.UploadFile(localFullPath, false); } /// <summary> /// 上传文件到服务器 /// </summary> /// <param name="localFullPath">要上传的本地文件全路径</param> /// <param name="overWriteFile">是否要重写服务器上的文件</param> public void UploadFile(string localFullPath, bool overWriteFile) { this.UploadFile(localFullPath, Path.GetFileName(localFullPath), overWriteFile); } /// <summary> /// 上传文件到服务器 /// /// </summary> /// <param name="localFullPath">要上传的本地文件全路径</param> /// <param name="remoteFileName">上传后文件重命名为</param> public void UploadFile(string localFullPath, string remoteFileName) { this.UploadFile(localFullPath, remoteFileName, false); } /// <summary> /// 上传文件到服务器 /// </summary> /// <param name="localFullPath">要上传的本地文件全路径</param> /// <param name="remoteFileName">上传后文件重命名为</param> /// <param name="overWriteFile">是否要重写服务器上的文件</param> public void UploadFile(string localFullPath, string remoteFileName, bool overWriteFile) { byte[] fileBytes = null; using (FileStream fileStream = new FileStream(localFullPath, FileMode.Open, FileAccess.Read)) { fileBytes = new byte[fileStream.Length]; fileStream.Read(fileBytes, 0, (Int32)fileStream.Length); } this.UploadFile(fileBytes, remoteFileName, overWriteFile); } /// <summary> /// 上传文件到服务器 /// </summary> /// <param name="fileBytes">上传文件的字节流</param> /// <param name="remoteFileName">上传后文件重命名为</param> public void UploadFile(byte[] fileBytes, string remoteFileName) { this.UploadFile(fileBytes, remoteFileName, false); } /// <summary> /// 上传文件到服务器 /// </summary> /// <param name="fileBytes">上传文件的字节流</param> /// <param name="remoteFileName">上传后文件重命名为</param> /// <param name="overWriteFile">是否要重写服务器上的文件</param> public void UploadFile(byte[] fileBytes, string remoteFileName, bool overWriteFile) { this.OpenResponse(overWriteFile ? remoteFileName : Gadget.ReturnFileNameWithCurrentDate(remoteFileName), WebRequestMethods.Ftp.UploadFile); using (Stream stream = this.request.GetRequestStream()) { using (MemoryStream memoryStream = new MemoryStream(fileBytes)) { byte[] buffer = new byte[Constant.FTP.LenOfBuffer]; int bytesRead = 0; int totalRead = 0; while (true) { bytesRead = memoryStream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } totalRead += bytesRead; stream.Write(buffer, 0, bytesRead); } } this.response = this.request.GetResponse() as FtpWebResponse; } } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> public void DownloadFile(string remoteFileName, string localPath) { this.DownloadFile(remoteFileName, localPath, false); } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> /// <param name="overWriteFile">是否要重写本地的文件</param> public void DownloadFile(string remoteFileName, string localPath, bool overWriteFile) { this.DownloadFile(remoteFileName, localPath, remoteFileName, overWriteFile); } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> /// <param name="localFileName">下载到本地的文件重命名为</param> public void DownloadFile(string remoteFileName, string localPath, string localFileName) { this.DownloadFile(remoteFileName, localPath, localFileName, false); } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> /// <param name="localFileName">下载到本地的文件重命名为</param> /// <param name="overWriteFile">是否要重写本地的文件</param> public void DownloadFile(string remoteFileName, string localPath, string localFileName, bool overWriteFile) { byte[] fileBytes = this.DownloadFile(remoteFileName); if (fileBytes != null) { using (FileStream fileStream = new FileStream(Path.Combine(localPath, overWriteFile ? localFileName : Gadget.ReturnFileNameWithCurrentDate(localFileName)), FileMode.Create)) { fileStream.Write(fileBytes, 0, fileBytes.Length); fileStream.Flush(); } } } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="RemoteFileName">要下载的服务器文件名</param> /// <returns>文件的字节流</returns> public byte[] DownloadFile(string RemoteFileName) { this.OpenResponse(RemoteFileName, WebRequestMethods.Ftp.DownloadFile); using (Stream stream = this.response.GetResponseStream()) { using (MemoryStream memoryStream = new MemoryStream(Constant.FTP.CapacityofMemeoryStream)) { byte[] buffer = new byte[Constant.FTP.LenOfBuffer]; int bytesRead = 0; int TotalRead = 0; while (true) { bytesRead = stream.Read(buffer, 0, buffer.Length); TotalRead += bytesRead; if (bytesRead == 0) break; memoryStream.Write(buffer, 0, bytesRead); } return memoryStream.Length > 0 ? memoryStream.ToArray() : null; } } } /// <summary> /// 删除服务器文件 /// </summary> /// <param name="directoryPath">要删除的文件路径</param> /// <param name="fileName">要删除的文件名</param> public void DeleteFile(string directoryPath, string fileName) { this.DeleteFile(directoryPath + fileName); } /// <summary> /// 删除服务器文件 /// </summary> /// <param name="fileName">要删除的文件名</param> public void DeleteFile(string fileName) { this.OpenResponse(fileName, WebRequestMethods.Ftp.DeleteFile); } /// <summary> /// 列出服务器上指定目录下的所有文件 /// </summary> /// <param name="directoryPath">指定的目录</param> /// <returns>文件名列表</returns> public string[] LisFiles(string directoryPath) { try { List<string> filesList = new List<string>(); this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectory); using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream(), System.Text.Encoding.Default)) { return Gadget.SplitString(streamReader.ReadToEnd(), Constant.TextConstant.FtpNewLine); } } catch { return null; } } /// <summary> /// 列出服务器上指定目录下的所有子目录 /// </summary> /// <param name="directoryPath">指定的目录</param> /// <returns>子目录名列表</returns> public string[] ListDirectories(string directoryPath) { List<string> directoriesList = new List<string>(); this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectoryDetails); using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream())) { string line = streamReader.ReadLine(); if (line != null) { while (line != null) { line = line.Substring(line.LastIndexOf(Constant.TextConstant.Colon) + Constant.FTP.LenToDirectory); if (!line.StartsWith(Constant.FileConstant.FileTypeSeperator)) { directoriesList.Add(line); } line = streamReader.ReadLine(); } return directoriesList.ToArray<string>(); } } return null; } /// <summary> /// 检查指定的目录是否在服务器上存在 /// </summary> /// <param name="directory">指定的目录</param> /// <returns>如果存在返回true,否则返回false</returns> public bool DirectoryExist(string directory) { try { this.OpenResponse(directory, WebRequestMethods.Ftp.GetDateTimestamp); return true; } catch (Exception) { return false; } } /// <summary> /// 检查指定的文件是否在服务器上存在 /// </summary> /// <param name="directoryPath">指定的目录</param> /// <param name="remoteFileName">指定的文件</param> /// <returns>如果存在返回true,否则返回false</returns> public bool FileExist(string directoryPath, string remoteFileName) { string[] fileNames = this.LisFiles(directoryPath); foreach (string fileName in fileNames) { if (string.Compare(fileName, remoteFileName, true) == 0) { return true; } } return false; } /// <summary> /// 释放资源 /// </summary> public void Dispose() { this.Close(); } /// <summary> /// 释放资源 /// </summary> public void Close() { if (this.response != null) { this.response.Close(); this.response = null; } } } 2、 public class Constant { public class TextConstant { public static readonly string Tab = " "; public static readonly string NewLine = " "; public static readonly string UnderLine = "_"; public static readonly string FtpNewLine = " "; public static readonly string Colon = ":"; } public class HtmlConstant { public static readonly string NewLine = "<br />"; } public class FileConstant { public static readonly string FileTypeForTXT = ".txt"; public static readonly string FileTypeForExcel = ".xls"; public static readonly string FileTypeForZip = ".zip"; public static readonly string FileTypeSeperator = "."; public static readonly string FileFullMatchSymbol = "*.*"; public static readonly string FolderSeperator = @""; } public class DatetimeFormat { public static readonly string YYMMDDHHMMSS = "yyMMddHHmmss"; } public class FTP { public static readonly int LenToDirectory = 4; public static readonly int LenOfBuffer = 1024; public static readonly int CapacityofMemeoryStream = 1024 * 500; } 3、 public class Gadget { public static bool CheckDataSetIsNullOrNot(DataSet dst) { return dst != null && dst.Tables.Count > 0 && dst.Tables[0].Rows.Count > 0; } public static string ReturnFileNameWithCurrentDate(string fileName) { return Path.GetFileNameWithoutExtension(fileName) + Constant.TextConstant.UnderLine + DateTime.Now.ToString(Constant.DatetimeFormat.YYMMDDHHMMSS) + Constant.FileConstant.FileTypeSeperator + Path.GetExtension(fileName); } public static string[] SplitString(string str, string split) { return str.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries); } }
FTP查看,下载,移动,删除,测试代码:
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Net; using System.Text; namespace DealerDailyJob { public class Helper { private string requestUriString = string.Empty; private string userName = string.Empty; private string password = string.Empty; private FtpWebRequest request; private FtpWebResponse response; /// <summary> /// 构造函数 /// </summary> /// <param name="RequestUriString">登陆IP</param> /// <param name="UserName">用户名</param> /// <param name="Password">密码</param> public Helper(string RequestUriString, string UserName, string Password) { this.requestUriString = "ftp://" + RequestUriString + "/"; this.userName = UserName; this.password = Password; } /// <summary> /// 创建FtpWebRequest /// </summary> /// <param name="uriString">FTP路径</param> /// <param name="method">FTP方法</param> private void OpenRequest(string uriString, string method) { try { this.request = WebRequest.Create(new Uri(this.requestUriString + uriString)) as FtpWebRequest; this.request.Credentials = new NetworkCredential(userName, password); this.request.UseBinary = true; this.request.Method = method; } catch { } } /// <summary> /// 返回FtpWebResponse /// </summary> /// <param name="uriString">FTP路径</param> /// <param name="method">FTP方法</param> private void OpenResponse(string uriString, string method) { try { this.OpenRequest(uriString, method); this.response = this.request.GetResponse() as FtpWebResponse; } catch { } } /// <summary> /// 删除ftp上的文件 /// </summary> /// <param name="file">服务器上的文件路径</param> public void Delete(string file) { this.OpenResponse(file, WebRequestMethods.Ftp.DeleteFile); } /// <summary> /// 移动ptf上的文件 /// </summary> /// <param name="uName">登录名</param> /// <param name="uPwd">密码</param> /// <param name="Name">文件</param> /// <param name="ftpServerIP">登陆地址</param> public void Cut(string uName, string uPwd, string Name,string ftpServerIP) { request = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/in/" + Name)); //x代表实际Ip,这里用未知数代替 request.Method = WebRequestMethods.Ftp.Rename; request.KeepAlive = false; request.RenameTo = "~/bk/" + Name; //这里用的是绝对路径,大家可以根据实际情况修改 request.UseBinary = true; request.Credentials = new NetworkCredential(uName, uPwd); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } /// <summary> /// 列出服务器上指定目录下的所有文件 /// </summary> /// <param name="directoryPath">指定的目录</param> /// <returns>文件名列表</returns> public string[] LisFiles(string directoryPath) { try { List<string> filesList = new List<string>(); this.OpenResponse(directoryPath, WebRequestMethods.Ftp.ListDirectory); using (StreamReader streamReader = new StreamReader(this.response.GetResponseStream(), System.Text.Encoding.Default)) { return Gadget.SplitString(streamReader.ReadToEnd(), Constant.TextConstant.FtpNewLine); } } catch { return null; } } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> public void DownloadFile(string remoteFileName, string localPath) { this.DownloadFile(remoteFileName, localPath, false); } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> /// <param name="overWriteFile">是否要重写本地的文件</param> public void DownloadFile(string remoteFileName, string localPath, bool overWriteFile) { this.DownloadFile(remoteFileName, localPath, remoteFileName, overWriteFile); } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> /// <param name="localFileName">下载到本地的文件重命名为</param> public void DownloadFile(string remoteFileName, string localPath, string localFileName) { this.DownloadFile(remoteFileName, localPath, localFileName, false); } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="remoteFileName">要下载的服务器文件名</param> /// <param name="localPath">下载到本地的路径</param> /// <param name="localFileName">下载到本地的文件重命名为</param> /// <param name="overWriteFile">是否要重写本地的文件</param> public void DownloadFile(string remoteFileName, string localPath, string localFileName, bool overWriteFile) { byte[] fileBytes = this.DownloadFile(remoteFileName); if (fileBytes != null) { using (FileStream fileStream = new FileStream(Path.Combine(localPath, overWriteFile ? localFileName : Gadget.ReturnFileNameWithCurrentDate(localFileName)), FileMode.Create)) { fileStream.Write(fileBytes, 0, fileBytes.Length); fileStream.Flush(); } } } /// <summary> /// 下载服务器文件到本地 /// </summary> /// <param name="RemoteFileName">要下载的服务器文件名</param> /// <returns>文件的字节流</returns> public byte[] DownloadFile(string RemoteFileName) { this.OpenResponse(RemoteFileName, WebRequestMethods.Ftp.DownloadFile); using (Stream stream = this.response.GetResponseStream()) { using (MemoryStream memoryStream = new MemoryStream(Constant.FTP.CapacityofMemeoryStream)) { byte[] buffer = new byte[Constant.FTP.LenOfBuffer]; int bytesRead = 0; int TotalRead = 0; while (true) { bytesRead = stream.Read(buffer, 0, buffer.Length); TotalRead += bytesRead; if (bytesRead == 0) break; memoryStream.Write(buffer, 0, bytesRead); } return memoryStream.Length > 0 ? memoryStream.ToArray() : null; } } } } public class Gadget { public static bool CheckDataSetIsNullOrNot(DataSet dst) { return dst != null && dst.Tables.Count > 0 && dst.Tables[0].Rows.Count > 0; } public static string ReturnFileNameWithCurrentDate(string fileName) { string name = Path.GetFileNameWithoutExtension(fileName) + Constant.TextConstant.UnderLine + DateTime.Now.ToString(Constant.DatetimeFormat.YYMMDDHHMMSS) + Constant.FileConstant.FileTypeSeperator + Path.GetExtension(fileName); return Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName); } public static string[] SplitString(string str, string split) { return str.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries); } } public class Constant { public class TextConstant { public static readonly string Tab = " "; public static readonly string NewLine = " "; public static readonly string UnderLine = "_"; public static readonly string FtpNewLine = " "; public static readonly string Colon = ":"; } public class HtmlConstant { public static readonly string NewLine = "<br />"; } public class FileConstant { public static readonly string FileTypeForTXT = ".txt"; public static readonly string FileTypeForExcel = ".xls"; public static readonly string FileTypeForZip = ".zip"; public static readonly string FileTypeSeperator = "."; public static readonly string FileFullMatchSymbol = "*.*"; public static readonly string FolderSeperator = @""; } public class DatetimeFormat { public static readonly string YYMMDDHHMMSS = "yyMMddHHmmss"; } public class FTP { public static readonly int LenToDirectory = 4; public static readonly int LenOfBuffer = 1024; public static readonly int CapacityofMemeoryStream = 1024 * 500; } } }