using System; using System.Configuration; using System.IO; using System.Net; using System.Text; namespace Demo { public class FtpHepler { private string ftpPassword = ConfigurationManager.AppSettings["FtpPassWord"]; private string ftpServerIP = ConfigurationManager.AppSettings["FtpIp"]; private string ftpUserID = ConfigurationManager.AppSettings["FtpUser"]; private string ftpRemotePath; private string ftpURI; /// <summary> /// 连接FTP /// </summary> /// <param name="FtpServerIP">FTP连接地址</param> /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param> /// <param name="FtpUserID">用户名</param> /// <param name="FtpPassword">密码</param> public FtpHepler(string FtpRemotePath) { ftpRemotePath = FtpRemotePath; ftpURI = "ftp://" + ftpServerIP + "/"; if (!string.IsNullOrEmpty(ftpRemotePath)) { ftpURI = ftpURI + ftpRemotePath.Trim('/') + "/"; } } //public FtpHepler(string FtpRemotePath,int jsType) //{ // if (jsType!=0) // { // this.ftpPassword = ConfigurationManager.AppSettings["JsFtpPassWord"]; // this.ftpServerIP = ConfigurationManager.AppSettings["JsFtpIp"]; // this.ftpUserID = ConfigurationManager.AppSettings["JsFtpUser"]; // } // ftpRemotePath = FtpRemotePath; // ftpURI = "ftp://" + ftpServerIP + "/"; // if (!string.IsNullOrEmpty(ftpRemotePath)) // { // ftpURI = ftpURI + ftpRemotePath.Trim('/') + "/"; // } //} public string GetFtpURI() { return ftpURI; } /// <summary> /// 上传 /// </summary> /// <param name="filename"></param> public void Upload(string filename) { var fileInf = new FileInfo(filename); var uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest) WebRequest.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; var buffLength = 2048; var buff = new byte[buffLength]; int contentLen; var fs = fileInf.OpenRead(); try { var 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) { Conwin.Framework.Log4net.LogHelper.Error("FTP上传失败",ex); } } /// <summary> /// 上传 /// </summary> /// <param name="filename"></param> public void Upload(byte[] stream, string FtpRemotePath) { var uri = ftpURI + FtpRemotePath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = stream.Length; try { using (var strm = reqFTP.GetRequestStream()) { strm.Write(stream, 0, stream.Length); } } catch (Exception ex) { } } /// <summary> /// 上传 /// </summary> /// <param name="filename"></param> public void Upload(Stream stream, string FtpRemotePath) { var uri = ftpURI + FtpRemotePath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = stream.Length; var buffLength = 2048; var buff = new byte[buffLength]; int contentLen; try { var strm = reqFTP.GetRequestStream(); contentLen = stream.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = stream.Read(buff, 0, buffLength); } strm.Close(); stream.Close(); } catch (Exception ex) { Conwin.Framework.Log4net.LogHelper.Error("FTP上传失败", ex); } } /// <summary> /// 上传 /// </summary> /// <param name="filename"></param> public void Upload(MemoryStream stream, string FtpRemotePath) { var uri = ftpURI + FtpRemotePath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = stream.Length; try { stream.Position = 0; var strm = reqFTP.GetRequestStream(); stream.CopyTo(strm); strm.Close(); stream.Close(); } catch (Exception ex) { Conwin.Framework.Log4net.LogHelper.Error("FTP上传失败", ex); } } /// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public string Download(string filePath, string fileName) { FtpWebRequest reqFTP; try { var outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); var response = (FtpWebResponse) reqFTP.GetResponse(); var ftpStream = response.GetResponseStream(); var cl = response.ContentLength; var bufferSize = 2048; int readCount; var 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) { return fileName + " 下载失败 --> " + ex.Message; } return string.Empty; } /// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public string Download1(string fileName, ref byte[] base64string) { FtpWebRequest reqFTP; Stream ftpStream = null; FtpWebResponse response = null; MemoryStream outputStream = null; try { outputStream = new MemoryStream(); reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); response = (FtpWebResponse) reqFTP.GetResponse(); ftpStream = response.GetResponseStream(); var cl = response.ContentLength; var bufferSize = 2048; int readCount; var buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } base64string = outputStream.ToArray(); //ftpStream.Close(); //outputStream.Close(); //response.Close(); } catch (Exception ex) { return fileName + " 下载失败 --> " + ex.Message; } finally { ftpStream?.Close(); outputStream?.Close(); response?.Close(); } return string.Empty; } /// <summary> /// 将流转化为二进制数组 /// </summary> /// <param name="stream"></param> /// <returns></returns> public byte[] StreamToBytes(Stream stream) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } /// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public string Download(string fileName, ref byte[] base64string) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); var response = (FtpWebResponse) reqFTP.GetResponse(); var ftpStream = response.GetResponseStream(); var cl = response.ContentLength; var bufferSize = base64string.Length; base64string = new byte[bufferSize]; ftpStream.Read(base64string, 0, bufferSize); ftpStream.Close(); response.Close(); } catch (Exception ex) { return fileName + " 下载失败 --> " + ex.Message; } return string.Empty; } /// <summary> /// 删除文件 /// </summary> /// <param name="fileName"></param> public string Delete(string fileName) { try { var uri = ftpURI + fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; var result = string.Empty; var response = (FtpWebResponse) reqFTP.GetResponse(); var size = response.ContentLength; var datastream = response.GetResponseStream(); var sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { return "删除失败 --> " + ex.Message + " 文件名:" + fileName; } return string.Empty; } /// <summary> /// 删除文件夹 /// </summary> /// <param name="folderName"></param> public void RemoveDirectory(string folderName) { try { var uri = ftpURI + folderName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; var result = string.Empty; var response = (FtpWebResponse) reqFTP.GetResponse(); var size = response.ContentLength; var datastream = response.GetResponseStream(); var sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { } } /// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> /// <returns></returns> public string[] GetFilesDetailList() { string[] downloadFiles; try { var result = new StringBuilder(); FtpWebRequest ftp; ftp = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI)); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; var response = ftp.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.Default); //while (reader.Read() > 0) //{ //} var line = reader.ReadLine(); //line = reader.ReadLine(); //line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } reader.Close(); response.Close(); if (!string.IsNullOrWhiteSpace(result.ToString())) { result.Remove(result.ToString().LastIndexOf("\n"), 1); return result.ToString().Split('\n'); } return null; } catch (Exception ex) { return null; } } /// <summary> /// 获取当前目录下文件列表(仅文件) /// </summary> /// <returns></returns> public string[] GetFileList(string mask) { var result = new StringBuilder(); FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI)); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; var response = reqFTP.GetResponse(); var reader = new StreamReader(response.GetResponseStream(), Encoding.Default); var line = reader.ReadLine(); while (line != null) { //if (line.ToLower().IndexOf(mask) > 0) //{ result.Append(line); result.Append("\n"); //} //if (mask.Trim() != string.Empty && mask.Trim() != "*.*") //{ // string mask_ = mask.Substring(0, mask.IndexOf("*")); // if (line.Substring(0, mask_.Length) == mask_) // { // result.Append(line); // result.Append("\n"); // } //} //else //{ // 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) { Conwin.Framework.Log4net.LogHelper.Fatal("filehelp",ex); throw ex; return null; } } /// <summary> /// 获取当前目录下所有的文件夹列表(仅文件夹) /// </summary> /// <returns></returns> public string[] GetDirectoryList() { var drectory = GetFilesDetailList(); var m = string.Empty; if (drectory != null) { foreach (var str in drectory) { var dirPos = str.IndexOf("<DIR>"); if (dirPos > 0) { /*判断 Windows 风格*/ m += str.Substring(dirPos + 5).Trim() + "\n"; } else if (str.Trim().Substring(0, 1).ToUpper() == "D") { /*判断 Unix 风格*/ //string dir = str.Substring(54).Trim(); var dir = str.Substring(49).Trim(); if (dir != "." && dir != "..") { m += dir + "\n"; } } } char[] n = {'\n'}; return m.Split(n); } return null; } /// <summary> /// 判断当前目录下指定的子目录是否存在 /// </summary> /// <param name="RemoteDirectoryName">指定的目录名</param> public bool DirectoryExist(string RemoteDirectoryName) { var dirList = GetDirectoryList(); if (dirList != null) { foreach (var str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } } return false; } /// <summary> /// 判断当前目录下指定的文件是否存在 /// </summary> /// <param name="RemoteFileName">远程文件名</param> public bool FileExist(string RemoteFileName) { var fileList = GetFileList("*.*"); foreach (var 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) WebRequest.Create(new Uri(ftpURI + dirName)); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); var response = (FtpWebResponse) reqFTP.GetResponse(); var ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { } } /// <summary> /// 获取指定文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> public long GetFileSize(string filename) { FtpWebRequest reqFTP; long fileSize = 0; try { reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + filename)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); var response = (FtpWebResponse) reqFTP.GetResponse(); var ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { } return fileSize; } /// <summary> /// 改名 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void ReName(string currentFilename, string newFilename) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest) WebRequest.Create(new Uri(ftpURI + currentFilename)); reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); var response = (FtpWebResponse) reqFTP.GetResponse(); var ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { } } /// <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 + "/"; } } }
标签:string,FTPHelper,Close,var,new,NET,reqFTP,response From: https://www.cnblogs.com/ZeroSunny/p/17025448.html