C# 实现FTP客户端的小例子
作者:Alan.hsiang 发布时间:2022-06-09 13:19:13
标签:c#,ftp,客户端
本文是利用C# 实现FTP客户端的小例子,主要实现上传,下载,删除等功能,以供学习分享使用。
思路:
通过读取FTP站点的目录信息,列出对应的文件及文件夹。
双击目录,则显示子目录,如果是文件,则点击右键,进行下载和删除操作。
通过读取本地电脑的目录,以树状结构展示,选择本地文件,右键进行上传操作。
涉及知识点:
FtpWebRequest【实现文件传输协议 (FTP) 客户端】 / FtpWebResponse【封装文件传输协议 (FTP) 服务器对请求的响应】Ftp的操作主要集中在两个类中。
FlowLayoutPanel 【流布局面板】表示一个沿水平或垂直方向动态排放其内容的面板。
ContextMenuStrip 【快捷菜单】 主要用于右键菜单。
资源文件:Resources 用于存放图片及其他资源。
效果图如下
左边:双击文件夹进入子目录,点击工具栏按钮‘上级目录'返回。文件点击右键进行操作。
右边:文件夹则点击前面+号展开。文件则点击右键进行上传。
核心代码如下
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FtpClient
{
public class FtpHelper
{
#region 属性与构造函数
/// <summary>
/// IP地址
/// </summary>
public string IpAddr { get; set; }
/// <summary>
/// 相对路径
/// </summary>
public string RelatePath { get; set; }
/// <summary>
/// 端口号
/// </summary>
public string Port { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 密码
/// </summary>
public string Password { get; set; }
public FtpHelper() {
}
public FtpHelper(string ipAddr, string port, string userName, string password) {
this.IpAddr = ipAddr;
this.Port = port;
this.UserName = userName;
this.Password = password;
}
#endregion
#region 方法
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filePath"></param>
/// <param name="isOk"></param>
public void DownLoad(string filePath, out bool isOk) {
string method = WebRequestMethods.Ftp.DownloadFile;
var statusCode = FtpStatusCode.DataAlreadyOpen;
FtpWebResponse response = callFtp(method);
ReadByBytes(filePath, response, statusCode, out isOk);
}
public void UpLoad(string file,out bool isOk)
{
isOk = false;
FileInfo fi = new FileInfo(file);
FileStream fs = fi.OpenRead();
long length = fs.Length;
string uri = string.Format("ftp://{0}:{1}{2}", this.IpAddr, this.Port, this.RelatePath);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential(UserName, Password);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.ContentLength = length;
request.Timeout = 10 * 1000;
try
{
Stream stream = request.GetRequestStream();
int BufferLength = 2048; //2K
byte[] b = new byte[BufferLength];
int i;
while ((i = fs.Read(b, 0, BufferLength)) > 0)
{
stream.Write(b, 0, i);
}
stream.Close();
stream.Dispose();
isOk = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally {
if (request != null)
{
request.Abort();
request = null;
}
}
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="isOk"></param>
/// <returns></returns>
public string[] DeleteFile(out bool isOk) {
string method = WebRequestMethods.Ftp.DeleteFile;
var statusCode = FtpStatusCode.FileActionOK;
FtpWebResponse response = callFtp(method);
return ReadByLine(response, statusCode, out isOk);
}
/// <summary>
/// 展示目录
/// </summary>
public string[] ListDirectory(out bool isOk)
{
string method = WebRequestMethods.Ftp.ListDirectoryDetails;
var statusCode = FtpStatusCode.DataAlreadyOpen;
FtpWebResponse response= callFtp(method);
return ReadByLine(response, statusCode, out isOk);
}
/// <summary>
/// 设置上级目录
/// </summary>
public void SetPrePath()
{
string relatePath = this.RelatePath;
if (string.IsNullOrEmpty(relatePath) || relatePath.LastIndexOf("/") == 0 )
{
relatePath = "";
}
else {
relatePath = relatePath.Substring(0, relatePath.LastIndexOf("/"));
}
this.RelatePath = relatePath;
}
#endregion
#region 私有方法
/// <summary>
/// 调用Ftp,将命令发往Ftp并返回信息
/// </summary>
/// <param name="method">要发往Ftp的命令</param>
/// <returns></returns>
private FtpWebResponse callFtp(string method)
{
string uri = string.Format("ftp://{0}:{1}{2}", this.IpAddr, this.Port, this.RelatePath);
FtpWebRequest request; request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.UseBinary = true;
request.UsePassive = true;
request.Credentials = new NetworkCredential(UserName, Password);
request.KeepAlive = false;
request.Method = method;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return response;
}
/// <summary>
/// 按行读取
/// </summary>
/// <param name="response"></param>
/// <param name="statusCode"></param>
/// <param name="isOk"></param>
/// <returns></returns>
private string[] ReadByLine(FtpWebResponse response, FtpStatusCode statusCode,out bool isOk) {
List<string> lstAccpet = new List<string>();
int i = 0;
while (true)
{
if (response.StatusCode == statusCode)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string line = sr.ReadLine();
while (!string.IsNullOrEmpty(line))
{
lstAccpet.Add(line);
line = sr.ReadLine();
}
}
isOk = true;
break;
}
i++;
if (i > 10)
{
isOk = false;
break;
}
Thread.Sleep(200);
}
response.Close();
return lstAccpet.ToArray();
}
private void ReadByBytes(string filePath,FtpWebResponse response, FtpStatusCode statusCode, out bool isOk)
{
isOk = false;
int i = 0;
while (true)
{
if (response.StatusCode == statusCode)
{
long length = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
using (FileStream outputStream = new FileStream(filePath, FileMode.Create))
{
using (Stream ftpStream = response.GetResponseStream())
{
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
}
}
break;
}
i++;
if (i > 10)
{
isOk = false;
break;
}
Thread.Sleep(200);
}
response.Close();
}
#endregion
}
/// <summary>
/// Ftp内容类型枚举
/// </summary>
public enum FtpContentType
{
undefined = 0,
file = 1,
folder = 2
}
}
FTP服务端和客户端示意图
来源:https://www.cnblogs.com/hsiang/p/7247801.html


猜你喜欢
- 泛型中占位符T和?有什么区别?这是一个好问题,有的人可能弄不清楚,所以我们这里简单的演示一下,相信大家一定能弄清楚的!先上两段代码:publ
- 1.线程与进程进程是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,线程则是一个实体,一个进程中至少有一个线程,是CPU
- 最近在写我们大三项目的一个视频文件上传的页面,实现后台对上传的进度进行监听,然后将监听的信息返回给前台页面。前台的页面效果图:前台进度条控件
- Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和
- 下面以launch方法为例进行分析。一.协程的创建launch方法的代码如下:// CoroutineScope的扩展方法public fu
- HTTP请求,在日常开发中,还是比较常见的,今天给大家分享HttpUtils如何使用。阅读本文,你将收获:简单总结HTTP请求常用配置;Ja
- 前言taptap-developer是一个spring boot框架驱动的纯Grpc服务,所以,只用了四步,移除了web和spring cl
- 在使用c#进行控制IIS服务启动停止的时候,提示:【无法打开计算机“.”上的 IISADMIN 服务】这种情况是发生在像vista、win7
- 最近做一个C#项目,需要对radis进行读写。首先引入System.Configuration,如下实现代码如下:public class
- @ApiModel使用场景在实体类上边使用,标记类时swagger的解析类概述提供有关swagger模型的其它信息,类将在操作中用作类型时自
- 背景最近引入了 Nacos Config 配置管理能力,说起来用法很简单,还是踩了三个坑。Nacos Config 的 nacos 的帐号密
- java的String对象底层是有字符数组存储的,理论上char[] 最大长度是int的最大值,实际思路:首先,String字面
- 在最近的项目中因为要用Android作为一个服务器去做一个实时接收数据的功能,所以这个时候就要去做一个Android本地的微型服务器。那么此
- 本文实例讲述了Java数组队列概念与用法。分享给大家供大家参考,具体如下:一.队列的概念 (1)队列也是一种线性结构(2)相比数组
- spring WEB MVC框架提供了一个MVC(model-view-controller)模型-视图-控制器的结构和组件,利用它可以开发
- 详解java中的PropertyChangeSupport与PropertyChangeListenerjava中的PropertyChan
- 下载Android SDK两种方式:(1)官网下载(需翻墙):https://developer.android.com/studio/in
- 引言C#5.0中async和await两个关键字,这两个关键字简化了异步编程,之所以简化了,还是因为编译器给我们做了更多的工作,下面就具体看
- 偶然间发现了Android.inputmethodservice.Keyboard类,即android可以自定义键盘类,做了一个简单例子供大
- 前言:有时候我们在用Spring Aop面向切面编程,需要获取连接点(JoinPoint)方法参数名、参数值。环境:Mac OSXIntel