C# FTP类,以前优化过一次,增加了对编码的识别,今天新增了主被动模式
2012-12-21 23:03
453 查看
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace ConsoleApplication1 { public class Ftp { string ftpServerIP; string ftpUserID; string ftpPassword; /// <summary> /// 主动模式是当进行文件下载时远程主机连接到本地主机的某端口进行数据发送,适用于本机网络端口开放较多。 /// 被动模式是当进行文件下载时本机主机连接到远程主机的某端口进行数据发送,适用于对端网络端口开放较多。 /// </summary> bool usePassive = false; FtpWebRequest reqFTP; /// <summary> /// ftp登录信息 /// </summary> /// <param name="ftpServerIP">ftpServerIP(例:221.1.217.92)</param> /// <param name="ftpUserID">ftpUserID</param> /// <param name="ftpPassword">ftpPassword</param> public Ftp(string ftpServerIP, string ftpUserID, string ftpPassword) { this.ftpServerIP = ftpServerIP; this.ftpUserID = ftpUserID; this.ftpPassword = ftpPassword; } public Ftp(string ftpServerIP, string ftpUserID, string ftpPassword, bool usePassive) { this.ftpServerIP = ftpServerIP; this.ftpUserID = ftpUserID; this.ftpPassword = ftpPassword; this.usePassive = usePassive; } #region 连接 /// <summary> /// 连接 /// </summary> /// <param name="path"></param> private void Connect(String path)//连接ftp { // 根据uri创建FtpWebRequest对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)); // 指定数据传输类型 reqFTP.UseBinary = true; reqFTP.UsePassive = usePassive; // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); } #endregion #region 获取文件列表 /// <summary> /// 获取文件列表 /// </summary> /// <param name="path"></param> /// <param name="WRMethods"></param> /// <param name="ResponseEncoding">编码方式</param> /// <returns></returns> private string[] GetFileList(string path, string WRMethods, System.Text.Encoding ResponseEncoding)//上面的代码示例了如何从ftp服务器上获得文件列表 { string[] downloadFiles; StringBuilder result = new StringBuilder(); try { Connect(path); reqFTP.Method = WRMethods; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), ResponseEncoding);//中文文件名 string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } // to remove the trailing '\n' result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { downloadFiles = null; return downloadFiles; } } public string[] GetFileList(string path, System.Text.Encoding ResponseEncoding) { if (path.Contains("ftp") == false) { return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory, ResponseEncoding); } else { return GetFileList(path, WebRequestMethods.Ftp.ListDirectory, ResponseEncoding); } } public string[] GetFileList(string path) { return GetFileList("ftp://" + ftpServerIP + "/" + path, System.Text.Encoding.GetEncoding("UTF-8")); } public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表 { return GetFileList(""); } #endregion #region 上传文件 /// <summary> /// 上传文件 /// </summary> /// <param name="filename">本地文件名</param> /// <param name="path">ftp路径</param> /// <param name="errorinfo"></param> public bool Upload(string filename, string path, out string errorinfo) //上面的代码实现了从ftp服务器上载文件的功能 { path = path.Replace("\\", "/"); FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" + path + "/" + fileInf.Name; DeleteFileName(fileInf.Name); Connect(uri);//连接 // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流(System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); errorinfo = "完成"; return true; } catch (Exception ex) { errorinfo = string.Format("因{0},无法完成上传", ex.Message); return false; } } #endregion #region 续传文件 /// <summary> /// 续传文件 /// </summary> /// <param name="filename"></param> public bool Upload(string filename, long size, string path, out string errorinfo) //上面的代码实现了从ftp服务器上载文件的功能 { path = path.Replace("\\", "/"); FileInfo fileInf = new FileInfo(filename); //string uri = "ftp://" + path + "/" + fileInf.Name; string uri = "ftp://" + path; Connect(uri);//连接 // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.AppendFile; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流(System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { StreamReader dsad = new StreamReader(fs); fs.Seek(size, SeekOrigin.Begin); // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); errorinfo = "完成"; return true; } catch (Exception ex) { errorinfo = string.Format("因{0},无法完成上传", ex.Message); return false; } } #endregion #region 下载文件 /// <summary> /// 下载文件 /// </summary> /// <param name="ftpfilepath">Ftp文件路径:例:"221.1.217.92/20100510.txt"</param> /// <param name="filePath">本地目录"c:\"</param> /// <param name="fileName">本地文件"1.txt"</param> /// <param name="errorinfo"></param> /// <returns></returns> public bool Download(string ftpfilepath, string LocalFilePath, string LocalFileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能 { try { LocalFilePath = LocalFilePath.Replace("我的电脑\\", ""); String onlyFileName = Path.GetFileName(LocalFileName); string newFileName = LocalFilePath + onlyFileName; if (File.Exists(newFileName)) { errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName); return false; } ftpfilepath = ftpfilepath.Replace("\\", "/"); string url = "ftp://" + ftpfilepath; Connect(url);//连接 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); FileStream outputStream = new FileStream(newFileName, FileMode.Create); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); errorinfo = ""; return true; } catch (Exception ex) { errorinfo = string.Format("因{0},无法下载", ex.Message); return false; } } #endregion #region 删除文件 /// <summary> /// 删除文件 /// </summary> /// <param name="fileName"></param> public void DeleteFileName(string fileName) { try { FileInfo fileInf = new FileInfo(fileName); string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name; Connect(uri);//连接 // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); response.Close(); } catch (Exception ex) { //MessageBox.Show(ex.Message, "删除错误"); } } #endregion #region 在ftp上创建目录 /// <summary> /// 在ftp上创建目录 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { try { string uri = "ftp://" + ftpServerIP + "/" + dirName; Connect(uri);//连接 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); response.Close(); } catch (Exception ex) { // MessageBox.Show(ex.Message); } } #endregion #region 删除ftp上目录 /// <summary> /// 删除ftp上目录 /// </summary> /// <param name="dirName"></param> public void delDir(string dirName) { try { string uri = "ftp://" + ftpServerIP + "/" + dirName; Connect(uri);//连接 reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); response.Close(); } catch (Exception ex) { // MessageBox.Show(ex.Message); } } #endregion #region 获得ftp上文件大小 /// <summary> /// 获得ftp上文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> public long GetFileSize(string filename) { long fileSize = 0; filename = filename.Replace("\\", "/"); try { // FileInfo fileInf = new FileInfo(filename); //string uri1 = "ftp://" + ftpServerIP + "/" + fileInf.Name; // string uri = filename; string uri = "ftp://" + filename; Connect(uri);//连接 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); fileSize = response.ContentLength; response.Close(); } catch (Exception ex) { // MessageBox.Show(ex.Message); } return fileSize; } #endregion #region ftp上文件改名 /// <summary> /// ftp上文件改名 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void Rename(string currentFilename, string newFilename) { try { FileInfo fileInf = new FileInfo(currentFilename); string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name; Connect(uri);//连接 reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); //Stream ftpStream = response.GetResponseStream(); //ftpStream.Close(); response.Close(); } catch (Exception ex) { // MessageBox.Show(ex.Message); } } #endregion } }
相关文章推荐
- 今天开始学模式识别与机器学习(PRML),章节5.1,Neural Networks神经网络-前向网络。
- 一次向svn中增加所有新增文件 svn add all new files
- 一次向svn中增加所有新增文件 svn add all new files
- 高效C#编码优化
- MVP设计模式的一次深入探索和优化
- 一次向svn中增加所有新增文件 svn add all new files
- 记一次查询超限的优化 单例模式的运用
- 一次向svn中增加所有新增文件 svn add all new files【转】
- 模式识别新研究:微软OCR两层优化提升自然场景下的文字识别精度
- 一次向svn中增加所有新增文件 svn add all new files
- HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。你会不会被他忽悠住?
- C#如何自动识别文件的编码
- 【出版直播】博客园征途系列,《设计模式——基于C#的工程化实现及扩展》今天上市,共飨博客园圣诞大餐
- c#编码优化
- C# HttpWebRequest访问页面时自动识别编码
- HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数
- CopyU!下一次更新将增加对设备厂商及型号的识别!
- 今天开始学模式识别与机器学习(PRML),章节5.1,Neural Networks神经网络-前向网络。
- 今天开始学习模式识别与机器学习Pattern Recognition and Machine Learning (PRML),章节5.1,Neural Networks神经网络-前向网络。
- C#自动识别文件编码