C# - VS2019WinFrm桌面应用程序FtpClient实现
前言
本篇主要记录:VS2019 WinFrm桌面应用程序实现简单的FtpClient,包含Ftp文件查看、上传和下载等功能。
准备工作
搭建WinFrm前台界面
添加必要的控件,这里主要应用到GroupBox、Label、TextBox和Button,如下图
核心代码
构造FtpHelper类
代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace FtpClientTest
{
public class FtpHelper
{
// FTP连接地址
string ftpServerIP;
// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
string ftpRemotePath;
// 用户名
string ftpUserID;
// 密码
string ftpPassword;
// 通用处理路径
string ftpURI; /// <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 + "/";
} /// <summary>
/// 上传
/// </summary>
/// <param name="filename">本地文件全路径</param>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = ftpURI + fileInf.Name;
FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.ContentLength = fileInf.Length;
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, , buffLength);
while (contentLen != )
{
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw new Exception("Ftphelper Upload Error --> " + ex.Message);
}
} /// <summary>
/// 下载
/// </summary>
/// <param name="filePath">文件保存本地路径</param>
/// <param name="fileName">Ftp上文件的路径</param>
public void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
} ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception("FtpHelper Download Error --> " + ex.Message);
}
} /// <summary>
/// 删除文件
/// </summary>
/// <param name="fileName">Ftp上文件的名称</param>
public void Delete(string fileName)
{
try
{
string uri = ftpURI + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.UsePassive = 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("FtpHelper Delete Error --> " + ex.Message + " 文件名:" + fileName);
}
} /// <summary>
/// 删除文件夹
/// </summary>
/// <param name="folderName">Ftp上文件夹的名称</param>
public void RemoveDirectory(string folderName)
{
try
{
string uri = ftpURI + folderName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
reqFTP.UsePassive = 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("FtpHelper Delete Error --> " + ex.Message + " 文件名:" + folderName);
}
} /// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
/// <returns></returns>
public string[] GetFilesDetailList()
{
string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftp.UsePassive = false;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); //while (reader.Read() > 0)
//{ //}
string line = reader.ReadLine();
//line = reader.ReadLine();
//line = reader.ReadLine(); while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
throw new Exception("FtpHelper Error --> " + ex.Message);
}
} /// <summary>
/// 获取当前目录下文件列表(仅文件)
/// </summary>
/// <returns></returns>
public string[] GetFileList(string mask)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
reqFTP.UsePassive = false;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine();
while (line != null)
{
if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
{ string mask_ = mask.Substring(, mask.IndexOf("*"));
if (line.Substring(, mask_.Length) == mask_)
{
result.Append(line);
result.Append("\n");
}
}
else
{
result.Append(line);
result.Append("\n");
}
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
{
throw new Exception("FtpHelper GetFileList Error --> " + ex.Message.ToString());
}
return downloadFiles;
}
} /// <summary>
/// 获取当前目录下所有的文件夹列表(仅文件夹)
/// </summary>
/// <returns></returns>
public string[] GetDirectoryList()
{
string[] drectory = GetFilesDetailList();
string m = string.Empty;
foreach (string str in drectory)
{
int dirPos = str.IndexOf("<DIR>");
if (dirPos > )
{
/*判断 Windows 风格*/
m += str.Substring(dirPos + ).Trim() + "\n";
}
else if (str.Trim().Substring(, ).ToUpper() == "D")
{
/*判断 Unix 风格*/
string dir = str.Substring().Trim();
if (dir != "." && dir != "..")
{
m += dir + "\n";
}
}
} char[] n = new char[] { '\n' };
return m.Split(n);
} /// <summary>
/// 判断当前目录下指定的子目录是否存在
/// </summary>
/// <param name="RemoteDirectoryName">指定的目录名</param>
public bool DirectoryExist(string RemoteDirectoryName)
{
string[] dirList = GetDirectoryList();
foreach (string str in dirList)
{
if (str.Trim() == RemoteDirectoryName.Trim())
{
return true;
}
}
return false;
} /// <summary>
/// 判断当前目录下指定的文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool FileExist(string RemoteFileName)
{
string[] fileList = GetFileList("*.*");
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
} /// <summary>
/// 创建文件夹
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
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("FtpHelper MakeDir Error --> " + ex.Message);
}
} /// <summary>
/// 获取指定文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = ;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength; ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception("FtpHelper GetFileSize Error --> " + ex.Message);
}
return fileSize;
} /// <summary>
/// 改名
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
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.UsePassive = false;
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("FtpHelper ReName Error --> " + ex.Message);
}
} /// <summary>
/// 移动文件
/// </summary>
/// <param name="currentFilename"></param>
/// <param name="newFilename"></param>
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
} /// <summary>
/// 切换当前目录
/// </summary>
/// <param name="DirectoryName"></param>
/// <param name="IsRoot">true 绝对路径 false 相对路径</param>
public void GotoDirectory(string DirectoryName, bool IsRoot)
{
if (IsRoot)
{
ftpRemotePath = DirectoryName;
}
else
{
ftpRemotePath += DirectoryName + "/";
}
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
} /// <summary>
/// 删除订单目录
/// </summary>
/// <param name="ftpServerIP">FTP 主机地址</param>
/// <param name="folderToDelete">FTP 用户名</param>
/// <param name="ftpUserID">FTP 用户名</param>
/// <param name="ftpPassword">FTP 密码</param>
public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword)
{
try
{
if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword))
{
FtpHelper fw = new FtpHelper(ftpServerIP, folderToDelete, ftpUserID, ftpPassword);
//进入订单目录
fw.GotoDirectory(folderToDelete, true);
//获取规格目录
string[] folders = fw.GetDirectoryList();
foreach (string folder in folders)
{
if (!string.IsNullOrEmpty(folder) || folder != "")
{
//进入订单目录
string subFolder = folderToDelete + "/" + folder;
fw.GotoDirectory(subFolder, true);
//获取文件列表
string[] files = fw.GetFileList("*.*");
if (files != null)
{
//删除文件
foreach (string file in files)
{
fw.Delete(file);
}
}
//删除冲印规格文件夹
fw.GotoDirectory(folderToDelete, true);
fw.RemoveDirectory(folder);
}
} //删除订单文件夹
string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/'));
string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + );
fw.GotoDirectory(parentFolder, true);
fw.RemoveDirectory(orderFolder);
}
else
{
throw new Exception("FTP 及路径不能为空!");
}
}
catch (Exception ex)
{
throw new Exception("删除订单时发生错误,错误信息为:" + ex.Message);
}
}
}
}
配合控件重写Ftp方法
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace FtpClientTest
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
} // 定义全局变量 ftp参数
private FtpHelper ftpHelper;
private string ipAddr;
private string port;
private string path;
private string userName;
private string password; /// <summary>
/// 方法:Ftp初始化
/// </summary>
private void FtpInit()
{
ipAddr = this.txtHost.Text;
port = this.txtHost.Text;
path = this.txtCurrentDir.Text;
userName = this.txtUserName.Text;
password = this.txtPassCode.Text;
ftpHelper = new FtpHelper(ipAddr, path, userName, password);
} /// <summary>
/// 事件:文件下载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDownLoad_Click(object sender, EventArgs e)
{
try
{
ftpHelper.Download(@"D:\", this.txtFilePath.Text.Trim());
MessageBox.Show("下载成功!", "提示");
}
catch (Exception ex)
{
MessageBox.Show("下载失败!错误信息[" + ex.Message + "]", "警告");
} }
/// <summary>
/// 方法:获取Ftp当前目录下的文件
/// </summary>
private void GetFileList()
{
string[] str = ftpHelper.GetFilesDetailList();
tbFileLists.Text = "";
for (int i = ; i < str.Length - ; i++)
{
if (tbFileLists.Text.ToString() == "")
{
tbFileLists.Text = str[i];
}
else
{
tbFileLists.Text = tbFileLists.Text + "\r\n" + str[i];
}
}
} /// <summary>
/// 事件:连接Ftp,获取文件列表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
FtpInit();
this.btnDownLoad.Enabled = true;
this.btnUpload.Enabled = true;
this.btnOpen.Enabled = true;
GetFileList();
}
catch (Exception ex)
{
this.btnDownLoad.Enabled = false;
this.btnUpload.Enabled = false;
this.btnOpen.Enabled = false;
MessageBox.Show("连接失败!错误信息[" + ex.Message + "]", "警告");
}
} /// <summary>
/// 事件:上传文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUpload_Click(object sender, EventArgs e)
{
try
{
ftpHelper.Upload(this.txtLocalFilePath.Text.Trim());
MessageBox.Show("上传成功!", "提示");
}
catch (Exception ex)
{
MessageBox.Show("上传失败!错误信息[" + ex.Message + "]", "警告");
}
} /// <summary>
/// 事件:选中需要上传的文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOpen_Click(object sender, EventArgs e)
{
// 创建 OpenFileDialog 对象
OpenFileDialog ofd = new OpenFileDialog();
// 设定默认打开文件类型,删选、设定文件显示类型
ofd.Filter = "(*.et;*.xls;*.xlsx)|*.et;*.xls;*.xlsx|all|*.*";
// 显示打开文件的窗口
ofd.ShowDialog();
// 获得选择的文件路径,并赋值给
this.txtLocalFilePath.Text = ofd.FileName;
}
}
}
实现效果
作者:Jeremy.Wu
出处:https://www.cnblogs.com/jeremywucnblog/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
C# - VS2019WinFrm桌面应用程序FtpClient实现的更多相关文章
- electron之Windows下使用 html js css 开发桌面应用程序
1.atom/electron github: https://github.com/atom/electron 中文文档: https://github.com/atom/electron/tree ...
- PHP-GTK 扩展(用PHP编写桌面应用程序)
PHP能做什么? PHP-GTK (构建桌面应用程序在PHP中使用PHP-GTK) 普及一下知识php如何做桌面客户端 [PHP技术]PHP开发Windows桌面应用程序实例 实战PHP/GTK 哪位 ...
- Cocos2dx集成于windows桌面窗口程序的步骤
2D游戏需要做编辑器,而编辑器总是希望可以复用游戏中的逻辑来运行场景试看效果. 对于cocos2dx开发的程序,这个需求可以描述为: 实现一种方法,在桌面窗口程序中的某个控件上显示cocos2dx的场 ...
- Android 在安装完成界面,点击打开应用程序。在应用程序点击home键,再从桌面打开程序导致产生多个实例或者说程序被重复打开
Android 在安装完成界面,点击打开应用程序.在应用程序点击home键,再从桌面打开程序导致产生多个实例或者说程序被重复打开. etong_123的专栏 - 博客频道 - CSDN.NET htt ...
- Android更改桌面应用程序launcher的两种方式
http://blog.csdn.net/mdx20072419/article/details/9632779/ launcher,也就是android的桌面应用程序.下图是我正在使用的魅族手机的l ...
- nodejs+chromium 创建桌面应用程序
直接用nodejs+javascript+html+css也可以创建桌面应用程序啦,前端开发的同学应该都比较感兴趣. 生成的应用程序自带nodejs环境和chrome浏览器环境. github的ato ...
- Visual Studio 2012 开发环境配置+控制台工具+桌面应用程序
一.界面布局视图设置 1.窗口的布局.控制台窗口运行恢复到开发环境的设置方法 也可以保存好设好的个性化设置,导入设置: 2.视图|服务器资源管理器(sever explorer) 可以访问数据源.服务 ...
- c#实现windows远程桌面连接程序
c#实现windows远程桌面连接程序 使用winform制作windows远程桌面连接程序,windows自带了远程桌面连接,我们需要将远程桌面连接集成 到自己的winform程序,并实现管理远程主 ...
- Microsoft Graph 桌面应用程序
作者:陈希章 发表于 2017年3月22日 桌面应用程序,在我这篇文章的语境中,我是特指在Windows桌面上面直接运行的.NET应用程序,包括Console Application,WPF Appl ...
随机推荐
- Set a One-to-Many Relationship设置一对多关系 (XPO)
In this lesson, you will learn how to set a one-to-many relationship between business objects. The C ...
- windows下dubbo-admin2.6.x之后版本的安装
安装zookeeper(单机) 下载bin.tar.gz的版本,解压 conf下的zoo_sample.cfg改zoo.cfg zoo.cfg里添加配置 dataDir=G:/zookeeper-/d ...
- [转]Oracle 11g R2 RAC高可用连接特性 – SCAN详解
原文地址:http://czmmiao.iteye.com/blog/2124373 昨天帮朋友解决11g RAC SCAN问题,当时为这朋友简单解答了一些SCAN特性相关的问题,但我知道这仅仅是 ...
- [b0028] python 归纳 (十三)_队列Queue在多线程中使用
# -*- coding: UTF-8 -*- """ 多线程同时读队列 总结: 1. 会阻塞 if self._jobq.qsize() > 0 进入逻辑,此时被 ...
- 6-SQL子查询
(1) 什么是关联子查询,什么是非关联子查询 (嵌套查询) 子查询从数据表中查询了数据结果,如果这个数据结果只执行一次,然后这个数据结果作为主查询的条件进行执行,那么这样的子查询叫做非关联子查询. 如 ...
- gn gen ninja
- [C2W3] Improving Deep Neural Networks : Hyperparameter tuning, Batch Normalization and Programming Frameworks
第三周:Hyperparameter tuning, Batch Normalization and Programming Frameworks 调试处理(Tuning process) 目前为止, ...
- UVA10559 方块消除 Blocks(区间dp)
一道区间dp好题,在GZY的ppt里,同时在洛谷题解里看见了Itst orz. 题目大意 有n个带有颜色的方块,没消除一段长度为 \(x\) 的连续的相同颜色的方块可以得到 \(x^2\) 的分数,用 ...
- SpringMVC环境搭建(二)
一.基于XML 1. 创建Maven Project,选择war,修改pom.xml SpringMVC是依赖于Spring的,需要导入核心包. <properties> <!-- ...
- BZOJ2733/LG3324 「HNOI2014」永无乡 权值线段树合并
问题描述 BZOJ2733 LG3224 题解 对于每个结点建立一棵权值线段树. 查询操作就去查询第 \(k\) 大,合并操作就合并两颗权值线段树. 并查集维护连通性. 同时 STO hkk,zcr, ...