C# 实现FTP客户端的小例子
作者:Alan.hsiang 时间:2022-06-09 13:19:13
本文是利用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
标签:c#,ftp,客户端
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
elasticsearch java客户端action的实现简单分析
2022-04-25 05:39:45
![](https://img.aspxhome.com/file/2023/4/83424_0s.jpg)
Maven引入本地Jar包并打包进War包中的方法
2023-06-16 12:43:28
![](https://img.aspxhome.com/file/2023/6/62966_0s.png)
Unity使用LineRender断笔写字
2023-01-07 09:29:38
![](https://img.aspxhome.com/file/2023/0/86950_0s.png)
java新人基础入门之递归调用
2023-11-10 01:15:16
![](https://img.aspxhome.com/file/2023/1/90981_0s.png)
Java包装类的概述与应用
2022-03-14 07:50:43
![](https://img.aspxhome.com/file/2023/0/91110_0s.png)
浅谈virtual、abstract方法和静态方法、静态变量理解
2022-08-29 02:29:14
MyBatis 如何获取子类的属性
2022-09-12 14:42:39
![](https://img.aspxhome.com/file/2023/0/63650_0s.png)
Mybatis无法获取带有下划线前缀的字段的值问题
2023-07-20 10:06:33
![](https://img.aspxhome.com/file/2023/3/62173_0s.png)
详解Mybatis极其(最)简(好)单(用)的一个分页插件
2021-09-25 03:00:35
多线程(多窗口卖票实例讲解)
2021-09-02 02:47:26
![](https://img.aspxhome.com/file/2023/9/61159_0s.png)
Autowired的注入过程源码解析
2022-04-29 17:53:36
![](https://img.aspxhome.com/file/2023/8/90018_0s.webp)
详解Java设计模式编程中的中介者模式
2021-09-24 02:48:54
![](https://img.aspxhome.com/file/2023/9/78959_0s.jpg)
SpringBoot整合Echarts实现用户人数和性别展示功能(详细步骤)
2023-02-22 00:31:59
![](https://img.aspxhome.com/file/2023/0/66530_0s.png)
Spring Cloud 的 Hystrix.功能及实践详解
2023-11-19 06:40:46
![](https://img.aspxhome.com/file/2023/9/59249_0s.jpg)
SpringBoot注解梳理(小结)
2023-11-10 13:27:19
elasticsearch集群发现zendiscovery的Ping机制分析
2021-05-25 05:40:55
![](https://img.aspxhome.com/file/2023/2/60572_0s.jpg)
Spring一步到位精通拦截器
2022-01-03 18:31:50
![](https://img.aspxhome.com/file/2023/5/68165_0s.png)
Spring缓存注解@Cacheable @CacheEvit @CachePut使用介绍
2022-06-05 01:47:14
常用Eclipse快捷方式(推荐)
2022-01-22 04:37:56
jQuery 动画效果代码分享
2023-11-24 00:10:12