C#实现FTP客户端的案例
作者:飞翔的月亮 发布时间:2023-06-15 19:46:47
标签: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
}
}
源码链接如下:案例
来源:http://www.cnblogs.com/hsiang/archive/2017/07/27/7247801.html


猜你喜欢
- String replace replaceFirst repaceAll区别replace(char oldChar, char newC
- 在.NET4.0中,我可以借助System.Speech组件让电脑来识别我们的声音。以上,当我说"name",显示&qu
- 1.首先,需要指定获取的文件夹,以及获取文件的文件名;文件夹:strLocalPath = System.Windows.Forms.App
- 队列的定义:队列(Queue)是只允许在一端进行插入,而在另一端进行删除的运算受限的线性表。 (1)允许删除的一端称为队头(Fro
- 这篇文章主要介绍了Java获取时间打印到控制台代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 一、简单介绍Unity 游戏实例开发集合,使用简单易懂的方式,讲解常见游戏的开发实现过程,方便后期类似游戏开发的借鉴和复用。本节介绍,Fly
- 一、Filter(过滤器)Filter接口定义在javax.servlet包中,是Servlet规范定义的,作用于Request/Respo
- 昨天有朋友在公众号发消息说看不懂await,async执行流,其实看不懂太正常了,因为你没经过社会的毒打,没吃过牢饭就不知道自由有多重要,没
- static和@Component遇到的bug今天在编写util的时候,发现不能调用到工具类里面的方法,转眼一看,原来不是工具类里面的方法是
- Android中判断网络是否连接实例详解在android中,如何监测网络的状态呢,这个有的时候也是十分重要的,方法如下:public cla
- 本文实例讲述了C#检测是否有u盘插入的方法。分享给大家供大家参考。具体如下:该C#代码可监控是否有u盘插入,同时可以监控其它驱动器的变化us
- 一、前言无论承接什么样的需求,是不是身边总有那么几个人代码写的烂,但是却时常有测试小姐姐过来聊天(求改bug)、有产品小伙伴送吃的(求写需求
- 什么是依赖注入首先,某个类的成员变量称为依赖,如若此变量想要实例化引用其类的方法,可以通过构造函数传参或者通过某个方法获取对象,此等通过外部
- 本文实例讲述了Java文本文件操作方法。分享给大家供大家参考。具体分析如下:最初Java是不支持对文本文件的处理的,为了弥补这个缺憾而引入了
- 双向信号和竞赛(Two-Way Signaling and Races) Monitor.Pulse方法的一个重要特性是它是异步执
- 问题,打一个页面cpu暴涨,打开一次就涨100%,一会系统就卡的不行了。排查方法,因为是线上的linux,没有用jvm监控工具rim链接上去
- 1.最常用的方法是创建一个计数器,判断是否遇到‘\0',不是'\0'指针就往后加一。int my_strlen(co
- @Order控制配置类/AOP/方法/字段的加载顺序1.AOP加载顺序 @Component &nbs
- Swing中的常用按钮在Swing中,常见的按钮组件有JButton,JCheckBox,JRadioButton等,它们都是抽象类Abst
- 测试1@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.NANOSECOND