因为工作中经常涉及到FTP文件的上传和下载,每次有这样的需求时都要重复编写相同的代码,后来干脆整理一个FTPClass,这样不仅方便自己使用,也可以共享给部门其它同事,使用时直接调用就可以了,节省了大家的开发时间。其实这个类网上有很多同样的写法,就算是给自己的博客凑篇文章吧。

目录

判断FTP连接

FTP文件上传

FTP文件下载

删除指定FTP文件

删除指定FTP文件夹

获取FTP上文件夹/文件列表

创建文件夹

获取指定FTP文件大小

更改指定FTP文件名称

移动指定FTP文件

应用示例


判断FTP连接

        public bool CheckFtp(){try{FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));// ftp用户名和密码ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;ftprequest.Timeout = 3000;FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();ftpResponse.Close();return true;}catch (Exception ex){return false;}}

FTP文件上传

参数localfile为要上传的本地文件,ftpfile为上传到FTP的文件名称,ProgressBar为显示上传进度的滚动条,适用于WinForm。若应用于控制台程序,只要重写该函数,将参数ProgressBar去掉即可,同时将函数实现里所有涉及ProgressBar的地方都删掉。

        public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb){FileInfo fileInf = new FileInfo(localfile);FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.UploadFile;reqFTP.KeepAlive = false;reqFTP.UseBinary = true;reqFTP.ContentLength = fileInf.Length;if (pb != null){pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;}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);if (pb != null){if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;}contentLen = fs.Read(buff, 0, buffLength);System.Windows.Forms.Application.DoEvents();}if (pb != null)pb.Value = pb.Maximum;System.Windows.Forms.Application.DoEvents();strm.Close();fs.Close();}catch (Exception ex){throw new Exception(ex.Message);}}

FTP文件下载

参数localfilename为将下载到本地的文件名称,ftpfilename为要下载的FTP上文件名称,ProcessBar为用于显示下载进度的进度条。该函数用于WinForm,若用于控制台,只要重写该函数,删除所有涉及ProcessBar的代码即可。

        public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb){long fileSize = GetFileSize(ftpfileName);if (fileSize > 0){if (pb != null){pb.Maximum = Convert.ToInt32(fileSize / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;}try{FileStream outputStream = new FileStream(localfilename, FileMode.Create);FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;reqFTP.UseBinary = true;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();int bufferSize = 2048;int readCount;byte[] buffer = new byte[bufferSize];readCount = ftpStream.Read(buffer, 0, bufferSize);while (readCount > 0){outputStream.Write(buffer, 0, readCount);if (pb != null){if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;}readCount = ftpStream.Read(buffer, 0, bufferSize);System.Windows.Forms.Application.DoEvents();}if (pb != null)pb.Value = pb.Maximum;System.Windows.Forms.Application.DoEvents();ftpStream.Close();outputStream.Close();response.Close();}catch (Exception ex){File.Delete(localfilename);throw new Exception(ex.Message);}}}

删除指定FTP文件

        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);}}

删除指定FTP文件夹

        public void RemoveDirectory(string urlpath){try{string uri = ftpURI + urlpath;FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.KeepAlive = false;reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;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);}}

获取FTP上文件夹/文件列表

ListType=1代表获取文件列表,ListType=2代表获取文件夹列表,ListType=3代表获取文件和文件夹列表。
Detail=true时获文件或文件夹详细信息,Detail=false时只获取文件或文件夹名称。
Keyword是只需list名称包含Keyword的文件或文件夹,若要list所有文件或文件夹,则该参数为空。若ListType=3,则该参数无效。

        public List<string> GetFileDirctoryList(int ListType, bool Detail, string Keyword){List<string> strs = new List<string>();try{FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));// ftp用户名和密码reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);if (Detail)reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;elsereqFTP.Method = WebRequestMethods.Ftp.ListDirectory;WebResponse response = reqFTP.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名string line = reader.ReadLine();while (line != null){if (ListType == 1){if (line.Contains(".")){if (Keyword.Trim() == "*.*" || Keyword.Trim() == ""){strs.Add(line);}else if (line.IndexOf(Keyword.Trim()) > -1){strs.Add(line);}}}else if (ListType == 2){if (!line.Contains(".")){if (Keyword.Trim() == "*" || Keyword.Trim() == ""){strs.Add(line);}else if (line.IndexOf(Keyword.Trim()) > -1){strs.Add(line);}}}else if (ListType == 3){strs.Add(line);}line = reader.ReadLine();}reader.Close();response.Close();return strs;}catch (Exception ex){throw new Exception(ex.Message);}}

创建文件夹

        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){throw new Exception(ex.Message);}}

获取指定FTP文件大小

        public long GetFileSize(string ftpfileName){long fileSize = 0;try{FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;reqFTP.UseBinary = true;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();fileSize = response.ContentLength;ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}return fileSize;}

更改指定FTP文件名称

        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){throw new Exception(ex.Message);}}

移动指定FTP文件

移动FTP文件其实就是重命名文件,只要将目标文件指定一个新的FTP地址就可以了。我没用过,不知道是否可行,因为C++是这么操作的。

        public void MovieFile(string currentFilename, string newDirectory){ReName(currentFilename, newDirectory);}

应用示例

将上面的内容打包到下面这个FTP类中,就可以在你的业务代码中调用了。

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;namespace TECSharpFunction
{/// <summary>/// FTP操作/// </summary>public class FTPHelper{#region FTPConfigstring ftpURI;string ftpUserID;string ftpServerIP;string ftpPassword;string ftpRemotePath;#endregion/// <summary>  /// 连接FTP服务器/// </summary>  /// <param name="FtpServerIP">FTP连接地址</param>  /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  /// <param name="FtpUserID">用户名</param>  /// <param name="FtpPassword">密码</param>  public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword){ftpServerIP = FtpServerIP;ftpRemotePath = FtpRemotePath;ftpUserID = FtpUserID;ftpPassword = FtpPassword;ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";}//把上面介绍的那些方法都放到下面}
}

举个例子:

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
uusing TECSharpFunction;namespace FTPTest
{public partial class Form1 : Form{public Form1(){InitializeComponent();}Public void FTP_Test(){FTPHelper ftpClient = new FTPHelper("192.168.1.1",@"/test","Test","Test");ftpClient.Download("test.txt", "test1.txt", progressBar1);}}
}

好了,就这样吧!

C# FTP操作(上传、下载等……)相关推荐

  1. [转]文件传输协议(FTP)操作(上传,下载,新建,删除,FTP间传送文件等)实现汇总1

    转自:http://blog.csdn.net/soarheaven/archive/2008/12/08/3474152.aspx 最近项目需要对FTP服务器进行操作,现把实现总结如下: 打算分2篇 ...

  2. Microsoft .NET Framework 2.0对文件传输协议(FTP)操作(上传,下载,新建,删除,FTP间传送文件等)实现汇总1...

    相关文章导航 Sql Server2005 Transact-SQL 新兵器学习总结之-总结 Flex,Fms3相关文章索引 FlexAir开源版-全球免费多人视频聊天室,免费网络远程多人视频会议系统 ...

  3. java ftp 下载慢_Java实现ftp文件上传下载解决慢中文乱码多个文件下载等问题

    废话不多说了,直接给大家贴代码了,具体代码如下所示: //文件上传 public static boolean uploadToFTP(String url,int port,String usern ...

  4. 关于FileZilla连接FTP站点上传下载文件

    关于FileZilla连接FTP站点上传下载文件 浏览器搜索FileZilla官网:https://www.filezilla.cn/download 根据自己操作系统安装 安装完成之后的启动界面是这 ...

  5. Linux 终端访问 FTP 及 上传下载 文件

    今天同事问我一个问题,在Linux 下访问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上. google 一下. ...

  6. Linux 终端訪问 FTP 及 上传下载 文件

    今天同事问我一个问题,在Linux 下訪问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上. google 一下. ...

  7. ftp文件推送 linux_Linux 终端访问 FTP 及 上传下载 文件

    今天同事问我一个问题,在Linux 下访问FTP,并将文件上传上去. 我之前一直是用WinSCP工具的. 先将文件从linux copy到windows下,然后在传到ftp上.google 一下. 方 ...

  8. C++:FTP文件上传下载(附完整源码)

    C++:FTP文件上传下载 FTP文件下载 FTP文件上传 FTP文件下载 #include #include #include #pragma comment(lib, "WinInet. ...

  9. Java通过FTP服务器上传下载文件的方法

    本文介绍了如何使用Apache Jakarta Commons Net(commons-net-3.3.jar)基于FileZilla Server服务器实现FTP服务器上文件的上传/下载/删除等操作 ...

  10. FTP的上传下载工具类

    下载commons-net的最新包,并引入至项目中. 以下为相关例子代码: package com.ffcs.icity.common.util;import java.io.File; import ...

最新文章

  1. 谁是全球最顶级AI实验室?
  2. soalris小記...
  3. 你们AI圈儿,已经引起了罗马教皇的警惕
  4. 【Ubuntu】Windows硬盘安装Ubuntu14.04
  5. C++ Primer 5th笔记(chap 15 OOP)访问控制与继承
  6. Spring中Bean的后置处理器
  7. andriod开发环境配置
  8. 技术干货 | mPaaS 框架下如何使用 Crash SDK 对闪退进行分析?
  9. php css去除h1样式,HTML中怎么设置h1的字体样式你知道吗?关于设置h1标签的样式详解...
  10. shadow阴影属性
  11. 排序算法第四篇——冒泡排序
  12. GMM-HMM语音识别原理详解 - 全文
  13. opencv-python:17_图像经典边缘检测算子(边缘检测、图像梯度、Roberts算子、Prewitt算子、Sobel 算子、Laplacian 算子、Canny算子、算子优缺点对比)
  14. ant design入门_Umi + ant Design Pro最简单的入门教程(一)初
  15. LimeSDR实验教程(3) GSM基站
  16. 发那科2021参数_FANUC常用参数
  17. 大名鼎鼎2006 7.2版
  18. 苹果CMS对接APP源码NVUE原生渲染
  19. 007 锁存器和触发器
  20. 密码学的安全性浅析4

热门文章

  1. C库源码中的移位函数
  2. Git error: cannot spawn ssh: No such file or directory的一个解决办法
  3. 机载点云单木分割方法和实现过程的概括介绍(论文赏析)
  4. Rasa课程、Rasa培训、Rasa面试、Rasa实战系列之UnexpecTED Intent Policy
  5. 系统集成项目管理工程师2021年下半年下午案例分析题及答案
  6. pda通用扫描app_智能仓储盘点——PDA扫码盘点APP真正实现“轻松盘点”!
  7. springMVC+jquery实现图片上传
  8. Android 12 首个开发者预览版到来
  9. matlab学习计划11.4
  10. 【C51单片机】交通红绿灯设计(仿真)