C# 实现FTP客户端的小例子 - 网站

C# 实现FTP客户端的小例子

分类:其他教程 · 发布时间:2021-10-04 22:57 · 阅读:5385

这篇文章主要介绍了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 属性与构造函数 ///  /// IP地址 ///  public string IpAddr { get; set; } ///  /// 相对路径 ///  public string RelatePath { get; set; } ///  /// 端口号 ///  public string Port { get; set; } ///  /// 用户名 ///  public string UserName { get; set; } ///  /// 密码 ///  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 方法 ///  /// 下载文件 ///  ///  ///  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; } } } ///  /// 删除文件 ///  ///  ///  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); } ///  /// 展示目录 ///  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); } ///  /// 设置上级目录 ///  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 私有方法 ///  /// 调用Ftp,将命令发往Ftp并返回信息 ///  /// 要发往Ftp的命令 ///  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; } ///  /// 按行读取 ///  ///  ///  ///  ///  private string[] ReadByLine(FtpWebResponse response, FtpStatusCode statusCode,out bool isOk) { List lstAccpet = new List(); 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 } ///  /// Ftp内容类型枚举 ///  public enum FtpContentType { undefined = 0, file = 1, folder = 2 } }

FTP服务端和客户端示意图

标签:
c# ftp 客户端

相关文章

C# async/await任务超时处理的实现

本文主要介绍了C# async/await任务超时处理的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

C#生成比较短的Token字符串

这篇文章介绍了C#生成Token字符串的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

C#中将dateTimePicker初始值设置为空

本文主要介绍了C#中将dateTimePicker初始值设置为空,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一文详解Go语言中的有限状态机FSM

有限状态机(Finite State Machine,FSM)是一种数学模型,用于描述系统在不同状态下的行为和转移条件。本文主要来和大家简单讲讲Go语言中的有限状态机FSM的使用,需要的可以参考一下

C#中程序自删除实现方法

这篇文章主要介绍了C# 程序自删除实现方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

返回分类 返回首页