服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#实现FTP客户端的案例

C#实现FTP客户端的案例

2022-01-17 12:53飞翔的月亮 C#

这篇文章主要为大家详细介绍了C#实现FTP客户端的小案例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文是利用C# 实现FTP客户端的小例子,主要实现上传,下载,删除等功能,以供学习分享使用。

思路:

通过读取FTP站点的目录信息,列出对应的文件及文件夹。
双击目录,则显示子目录,如果是文件,则点击右键,进行下载和删除操作。
通过读取本地电脑的目录,以树状结构展示,选择本地文件,右键进行上传操作。

涉及知识点:

FtpWebRequest【实现文件传输协议 (FTP) 客户端】 / FtpWebResponse【封装文件传输协议 (FTP) 服务器对请求的响应】Ftp的操作主要集中在两个类中。
FlowLayoutPanel  【流布局面板】表示一个沿水平或垂直方向动态排放其内容的面板。
ContextMenuStrip 【快捷菜单】 主要用于右键菜单。
资源文件:Resources 用于存放图片及其他资源。

效果图如下

左边:双击文件夹进入子目录,点击工具栏按钮‘上级目录'返回。文件点击右键进行操作。

右边:文件夹则点击前面+号展开。文件则点击右键进行上传。

C#实现FTP客户端的案例

核心代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
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

延伸 · 阅读

精彩推荐
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11