文章目录

  • 判断FTP连接
  • FTP文件上传
  • FTP文件下载
  • 删除指定FTP文件
  • 删除指定FTP文件夹
  • 获取FTP上文件夹/文件列表
  • 创建文件夹
  • 获取指定FTP文件大小
  • 更改指定FTP文件名称
  • 移动指定FTP文件
  • 应用示例
  • 举个例子:

判断FTP连接

public bool CheckFtp()
{try{FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));// ftp用户名和密码ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;ftprequest.Timeout = 3000;FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();ftpResponse.Close();return true;}catch (Exception ex){return false;}
}

FTP文件上传

参数localfile为要上传的本地文件,ftpfile为上传到FTP的文件名称,ProgressBar为显示上传进度的滚动条,适用于WinForm。若应用于控制台程序,只要重写该函数,将参数ProgressBar去掉即可,同时将函数实现里所有涉及ProgressBar的地方都删掉。

public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb)
{FileInfo fileInf = new FileInfo(localfile);FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.UploadFile;reqFTP.KeepAlive = false;reqFTP.UseBinary = true;reqFTP.ContentLength = fileInf.Length;if (pb != null){pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;}int buffLength = 2048;byte[] buff = new byte[buffLength];int contentLen;FileStream fs = fileInf.OpenRead();try{Stream strm = reqFTP.GetRequestStream();contentLen = fs.Read(buff, 0, buffLength);while (contentLen != 0){strm.Write(buff, 0, contentLen);if (pb != null){if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;}contentLen = fs.Read(buff, 0, buffLength);System.Windows.Forms.Application.DoEvents();}if (pb != null)pb.Value = pb.Maximum;System.Windows.Forms.Application.DoEvents();strm.Close();fs.Close();}catch (Exception ex){throw new Exception(ex.Message);}
}

FTP文件下载

参数localfilename为将下载到本地的文件名称,ftpfilename为要下载的FTP上文件名称,ProcessBar为用于显示下载进度的进度条。该函数用于WinForm,若用于控制台,只要重写该函数,删除所有涉及ProcessBar的代码即可。

public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb)
{long fileSize = GetFileSize(ftpfileName);if (fileSize > 0){if (pb != null){pb.Maximum = Convert.ToInt32(fileSize / 2048);pb.Maximum = pb.Maximum + 1;pb.Minimum = 0;pb.Value = 0;}try{FileStream outputStream = new FileStream(localfilename, FileMode.Create);FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;reqFTP.UseBinary = true;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();int bufferSize = 2048;int readCount;byte[] buffer = new byte[bufferSize];readCount = ftpStream.Read(buffer, 0, bufferSize);while (readCount > 0){outputStream.Write(buffer, 0, readCount);if (pb != null){if (pb.Value != pb.Maximum)pb.Value = pb.Value + 1;}readCount = ftpStream.Read(buffer, 0, bufferSize);System.Windows.Forms.Application.DoEvents();}if (pb != null)pb.Value = pb.Maximum;System.Windows.Forms.Application.DoEvents();ftpStream.Close();outputStream.Close();response.Close();}catch (Exception ex){File.Delete(localfilename);throw new Exception(ex.Message);}}
}

删除指定FTP文件

 public void Delete(string fileName){try{FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;reqFTP.KeepAlive = false;string result = String.Empty;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();long size = response.ContentLength;Stream datastream = response.GetResponseStream();StreamReader sr = new StreamReader(datastream);result = sr.ReadToEnd();sr.Close();datastream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}}

删除指定FTP文件夹

 public void RemoveDirectory(string urlpath){try{string uri = ftpURI + urlpath;FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.KeepAlive = false;reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;string result = String.Empty;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();long size = response.ContentLength;Stream datastream = response.GetResponseStream();StreamReader sr = new StreamReader(datastream);result = sr.ReadToEnd();sr.Close();datastream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}}

获取FTP上文件夹/文件列表

ListType=1代表获取文件列表,ListType=2代表获取文件夹列表,ListType=3代表获取文件和文件夹列表。
Detail=true时获文件或文件夹详细信息,Detail=false时只获取文件或文件夹名称。
Keyword是只需list名称包含Keyword的文件或文件夹,若要list所有文件或文件夹,则该参数为空。若ListType=3,则该参数无效。

public List<string> GetFileDirctoryList(int ListType, bool Detail, string Keyword)
{List<string> strs = new List<string>();try{FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));// ftp用户名和密码reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);if (Detail)reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;elsereqFTP.Method = WebRequestMethods.Ftp.ListDirectory;WebResponse response = reqFTP.GetResponse();StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名string line = reader.ReadLine();while (line != null){if (ListType == 1){if (line.Contains(".")){if (Keyword.Trim() == "*.*" || Keyword.Trim() == ""){strs.Add(line);}else if (line.IndexOf(Keyword.Trim()) > -1){strs.Add(line);}}}else if (ListType == 2){if (!line.Contains(".")){if (Keyword.Trim() == "*" || Keyword.Trim() == ""){strs.Add(line);}else if (line.IndexOf(Keyword.Trim()) > -1){strs.Add(line);}}}else if (ListType == 3){strs.Add(line);}line = reader.ReadLine();}reader.Close();response.Close();return strs;}catch (Exception ex){throw new Exception(ex.Message);}
}

创建文件夹

  public void MakeDir(string dirName){FtpWebRequest reqFTP;try{reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;reqFTP.UseBinary = true;reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}}

获取指定FTP文件大小

public long GetFileSize(string ftpfileName)
{long fileSize = 0;try{FtpWebRequest reqFTP;reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;reqFTP.UseBinary = true;FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();fileSize = response.ContentLength;ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}return fileSize;
}

更改指定FTP文件名称

public void ReName(string currentFilename, string newFilename)
{FtpWebRequest reqFTP;try{reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));reqFTP.Method = WebRequestMethods.Ftp.Rename;reqFTP.RenameTo = newFilename;reqFTP.UseBinary = true;reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();Stream ftpStream = response.GetResponseStream();ftpStream.Close();response.Close();}catch (Exception ex){throw new Exception(ex.Message);}
}

移动指定FTP文件

移动FTP文件其实就是重命名文件,只要将目标文件指定一个新的FTP地址就可以了。我没用过,不知道是否可行,因为C++是这么操作的。

public void MovieFile(string currentFilename, string newDirectory)
{ReName(currentFilename, newDirectory);
}

应用示例

将上面的内容打包到下面这个FTP类中,就可以在你的业务代码中调用了。

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;namespace TECSharpFunction
{/// <summary>/// FTP操作/// </summary>public class FTPHelper{#region FTPConfigstring ftpURI;string ftpUserID;string ftpServerIP;string ftpPassword;string ftpRemotePath;#endregion/// <summary>  /// 连接FTP服务器/// </summary>  /// <param name="FtpServerIP">FTP连接地址</param>  /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>  /// <param name="FtpUserID">用户名</param>  /// <param name="FtpPassword">密码</param>  public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword){ftpServerIP = FtpServerIP;ftpRemotePath = FtpRemotePath;ftpUserID = FtpUserID;ftpPassword = FtpPassword;ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";}//把上面介绍的那些方法都放到下面}
}

举个例子:

using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
uusing TECSharpFunction;namespace FTPTest
{public partial class Form1 : Form{public Form1(){InitializeComponent();}Public void FTP_Test(){FTPHelper ftpClient = new FTPHelper("192.168.1.1",@"/test","Test","Test");ftpClient.Download("test.txt", "test1.txt", progressBar1);}}
}

好了,就这样吧!
————————————————
版权声明:本文为CSDN博主「只会搬运的小菜鸟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011465910/article/details/126563124

c# FTP服务器文件上传下载等操作相关推荐

  1. 文件上传到ftp服务器大小变小,ftp服务器文件上传大小设置

    ftp服务器文件上传大小设置 内容精选 换一换 文件选择上传控件,用于上传文件. Windows场景中,当把源端服务器迁移到华为云后,目的端服务器C盘的已用空间比对应源端服务器C盘的已用空间大至少1G ...

  2. 华为服务器上传文件后怎么通过链接查看,远程服务器文件上传后的操作

    远程服务器文件上传后的操作 内容精选 换一换 本节指导您基于Linux操作系统环境完成镜像文件快速导入,推荐使用云平台的EulerOS云服务器作为转换镜像格式和生成位表文件的环境.Linux操作系统环 ...

  3. java jsch下载文件,JSch使用sftp协议实现服务器文件上传下载操作

    Jsch是什么? JSch 是SSH2的一个纯Java实现.它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等.你可以将它的功能集成到你自己的 程序中.同时该项目也提供一个J2 ...

  4. python实现TCP远程服务器文件上传,下载系统

    TCP服务器代码如下: from socket import *def client_upload(client_socket):"""上传数据""& ...

  5. Mac使用终端ssh对服务器文件上传下载(实用!)

    原博链接:https://blog.csdn.net/zcl_666/article/details/52240511#comments 在windows系统下有xshell可以很方便的登录服务器上传 ...

  6. cypress之实现文件上传下载以及操作iframe下页面元素

    前面讲解了使用cypress框架如何定位.操作页面元素以及校验测试结果,此次课程将介绍如何实现文件上传.操作iframe下面的页面原因以及操作shadow dom下的页面元素.为了完成此次课程目标,拆 ...

  7. linux搭建ftp服务器可上传下载,通过linux系统搭建ftp服务然后使用filezilla客户端进行上传下载...

    1.         准备环境 一台linux主机作为ftp服务器(这里以centos7.2系统为例),一台Windows系统的主机作为客户端 2.         服务端配置: (1)   下载vs ...

  8. java操作文件_java操作FTP,实现文件上传下载删除操作

    上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...

  9. 东软JavaWeb实训记-DAY8-小组项目开发实践(文件上传下载等操作)

    项目结构 其他: 源代码: package com.neu.dao;public class FileInfoDao extends BaseDao {public FileInfoDao() {su ...

最新文章

  1. usaco ★Zero Sum 和为零
  2. uinty粒子系统子物体变大_Unity2018粒子系统全息讲解,坑深慎入(3)
  3. C. Jon Snow and his Favourite Number DP + 注意数值大小
  4. mysql8安装版安装教程_MySQL8.0版本安装教程
  5. Elasticsearch--springcloud整合 high-level-client-测试-复杂检索---全文检索引擎ElasticSearch工作笔记025
  6. 手机开启热点给其他设备上网和用插卡随身路由给其他设备上网有何区别呢?
  7. leetcode946. Validate Stack Sequences
  8. 写出常用的5个linux命令 并解释,【PHP面试题】写出尽可能多的Linux命令。
  9. 用r语言分析janeausten_R语言相关性分析
  10. 轻量级日志收集转发 | fluent-bit配置详解(二)
  11. 计算机组成原理学习笔记-加法器
  12. 小程序自定义下拉刷新
  13. android p 小米6,小米6还能再战几年!将升级Android P
  14. 开发游戏十年,遭遇游戏开发史上最诡异事件,然而被我成功解决了!
  15. 大话设计模式之爱你一万年:第三章 创建型模式:工厂模式:我想让你坐在宝马里笑:5.工厂模式之抽象工厂模式
  16. Cisco Packet Tracer中配置单区域OSPF
  17. iOS生成图片分享到微信的一种方法
  18. echarts折线图设置横向基准线/水平线,超过基准线时折线会变色
  19. NKOJ 2703 (WC 2014)紫荆花之恋 (点分治+平衡树+替罪羊)
  20. 【JavaEE】文件

热门文章

  1. 低成本蓝牙芯片MS1656智能空调伴侣方案
  2. 2023年中国碳纤维行业报告
  3. 偷偷爆料下各公司年终奖情况!(1.30 日最新版)
  4. RGB3DS道路表观病害信息智慧检测系统:自研技术,助力道路运维提效降本
  5. HTML+CSS(详细版)
  6. matlab 中disp()函数用法
  7. 物理地址、逻辑地址、虚拟内存
  8. [实践篇]13.10 分析slog2info日志拆解qvm重启过程
  9. html左边移动属性,css左边偏移属性left、右边偏移属性right
  10. 华为云 Centos7 安全组配置好443端口后外网依然无法访问,telnet 测试端口失败,排查防火墙443端口是否开放