C#调用第三方工具完成FTP操作
作者:springsnow 发布时间:2021-08-23 09:52:48
标签:C#,第三方,工具,FTP,操作
一、FileZilla
Filezilla分为client和server。其中FileZilla Server是Windows平台下一个小巧的第三方FTP服务器软件,系统资源也占用非常小,可以让你快速简单的建立自己的FTP服务器。
打开FileZilla,进行如下操作
下图红色区域就是linux系统的文件目录,可以直接把windows下的文件直接拖拽进去。
二、WinSCP
跟FileZilla一样,也是一款十分方便的文件传输工具。WinSCP是连接Windows和Linux的。
WinSCP .NET Assembly and SFTP
https://winscp.net/eng/docs/library#csharp
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
}
三、FluentFTP
FluentFTP是一款老外开发的基于.Net的支持FTP及的FTPS 的FTP类库,FluentFTP是完全托管的FTP客户端,被设计为易于使用和易于扩展。它支持文件和目录列表,上传和下载文件和SSL / TLS连接。
它底层由Socket实现,可以连接到Unix和Windows IIS建立FTP的服务器,
github:https://github.com/robinrodricks/FluentFTP
举例:
// create an FTP client
FtpClient client = new FtpClient("123.123.123.123");
// if you don't specify login credentials, we use the "anonymous" user account
client.Credentials = new NetworkCredential("david", "pass123");
// begin connecting to the server
client.Connect();
// get a list of files and directories in the "/htdocs" folder
foreach (FtpListItem item in client.GetListing("/htdocs")) {
// if this is a file
if (item.Type == FtpFileSystemObjectType.File){
// get the file size
long size = client.GetFileSize(item.FullName);
}
// get modified date/time of the file or folder
DateTime time = client.GetModifiedTime(item.FullName);
// calculate a hash for the file on the server side (default algorithm)
FtpHash hash = client.GetHash(item.FullName);
}
// upload a file
client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/big.txt");
// rename the uploaded file
client.Rename("/htdocs/big.txt", "/htdocs/big2.txt");
// download the file again
client.DownloadFile(@"C:\MyVideo_2.mp4", "/htdocs/big2.txt");
// delete the file
client.DeleteFile("/htdocs/big2.txt");
// delete a folder recursively
client.DeleteDirectory("/htdocs/extras/");
// check if a file exists
if (client.FileExists("/htdocs/big2.txt")){ }
// check if a folder exists
if (client.DirectoryExists("/htdocs/extras/")){ }
// upload a file and retry 3 times before giving up
client.RetryAttempts = 3;
client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/big.txt", FtpExists.Overwrite, false, FtpVerify.Retry);
// disconnect! good bye!
client.Disconnect();
对FluentFTP部分操作封装类
public class FtpFileMetadata
{
public long FileLength { get; set; }
public string MD5Hash { get; set; }
public DateTime LastModifyTime { get; set; }
}
public class FtpHelper
{
private FtpClient _client = null;
private string _host = "127.0.0.1";
private int _port = 21;
private string _username = "Anonymous";
private string _password = "";
private string _workingDirectory = "";
public string WorkingDirectory
{
get
{
return _workingDirectory;
}
}
public FtpHelper(string host, int port, string username, string password)
{
_host = host;
_port = port;
_username = username;
_password = password;
}
public Stream GetStream(string remotePath)
{
Open();
return _client.OpenRead(remotePath);
}
public void Get(string localPath, string remotePath)
{
Open();
_client.DownloadFile(localPath, remotePath, true);
}
public void Upload(Stream s, string remotePath)
{
Open();
_client.Upload(s, remotePath, FtpExists.Overwrite, true);
}
public void Upload(string localFile, string remotePath)
{
Open();
using (FileStream fileStream = new FileStream(localFile, FileMode.Open))
{
_client.Upload(fileStream, remotePath, FtpExists.Overwrite, true);
}
}
public int UploadFiles(IEnumerable<string> localFiles, string remoteDir)
{
Open();
List<FileInfo> files = new List<FileInfo>();
foreach (var lf in localFiles)
{
files.Add(new FileInfo(lf));
}
int count = _client.UploadFiles(files, remoteDir, FtpExists.Overwrite, true, FtpVerify.Retry);
return count;
}
public void MkDir(string dirName)
{
Open();
_client.CreateDirectory(dirName);
}
public bool FileExists(string remotePath)
{
Open();
return _client.FileExists(remotePath);
}
public bool DirExists(string remoteDir)
{
Open();
return _client.DirectoryExists(remoteDir);
}
public FtpListItem[] List(string remoteDir)
{
Open();
var f = _client.GetListing();
FtpListItem[] listItems = _client.GetListing(remoteDir);
return listItems;
}
public FtpFileMetadata Metadata(string remotePath)
{
Open();
long size = _client.GetFileSize(remotePath);
DateTime lastModifyTime = _client.GetModifiedTime(remotePath);
return new FtpFileMetadata()
{
FileLength = size,
LastModifyTime = lastModifyTime
};
}
public bool TestConnection()
{
return _client.IsConnected;
}
public void SetWorkingDirectory(string remoteBaseDir)
{
Open();
if (!DirExists(remoteBaseDir))
MkDir(remoteBaseDir);
_client.SetWorkingDirectory(remoteBaseDir);
_workingDirectory = remoteBaseDir;
}
private void Open()
{
if (_client == null)
{
_client = new FtpClient(_host, new System.Net.NetworkCredential(_username, _password));
_client.Port = 21;
_client.RetryAttempts = 3;
if (!string.IsNullOrWhiteSpace(_workingDirectory))
{
_client.SetWorkingDirectory(_workingDirectory);
}
}
}
}
来源:https://www.cnblogs.com/springsnow/p/10149301.html


猜你喜欢
- 本文实例讲述了Android ActionBar搜索功能用法。分享给大家供大家参考,具体如下:使用ActionBar SearchView时
- 一、模拟业务需求假设我们现在需要在我们的系统中导入一批关于学生信息的Excel的数据,其主要的信息有:学号、姓名、年龄、性别等等,在导入系统
- 枚举类型是一种的值类型,它用于声明一组命名的常数。(1)枚举的声明:枚举声明用于声明新的枚举类型。访问修辞符 enum 枚举名:基础类型&n
- 概述本文基于示例的方式解释控制反转,再看控制反转之前,我们先看下常规控制流程,以数据库访问为例示例并没有实际访问数据,而是基于service
- 大家好,好久不见了,最近由于工作特别繁忙,已经有一个多月的时间没写博客了,我也是深感惭愧。那么今天的这篇既然是阔别了一个多月的文章,当然要带
- 前言本文主要介绍了关于spring boot中servlet启动过程与原理的相关内容,下面话不多说了,来一起看看详细的介绍吧启动过程与原理:
- 文章描述在前面两篇写完了对于GIF动态图片的分割和合成,这一篇来写下将视频文件分割成一帧帧图片的方法。开发环境.NET Framework版
- 本文介绍spring-rest接口中的LocalDateTime日期类型转时间戳的方法。具体的代码参照示例项目 https://github
- 不过我写的比较草率,代码结构不是很好,也没有体现OOP的思想,这几天有空会重构一下。先把代码发出来:public class MatrixC
- import java.io.*;import java.text.SimpleDateFormat;import java.util.*;
- XML的主要用途--数据存储和数据描述--是一个优良的配置文件--相当于一个小型数据库--XML不依赖于任何一种编程语言,是独立的W3C提供
- 样式效果 还是先来看效果: 这是一个仿雷达扫描的效果,是之前在做地图sdk接入时就想实现的效果,但之前由于赶着毕业设
- 1 二叉排序树的概述本文没有介绍一些基础知识。对于常见查找算法,比如顺序查找、二分查找、插入查找、斐波那契查找还不清楚的,可以看这篇文章:常
- #include<iostream>using namespace std;//非递归求解所有的子集void fun(int a
- 在一个完整的项目中,如果每一个控制器的方法都返回不同的结果,那么对项目的维护和扩展都会很麻烦;并且现在主流的开发模式时前后端分离的模式,如果
- 引言备忘录模式经常可以遇到,譬如下面这些场景:浏览器回退:浏览器一般有浏览记录,当我们在一个网页上点击几次链接之后,可在左上角点击左箭头回退
- 本文为大家分享了java实现学生选课系统的具体代码,供大家参考,具体内容如下案例要求:学生(学号,姓名,专业,所选课程{<3}) 老师
- 1.类成员与方法的可见性最小化举例:如果是一个private的方法,想删除就删除如果一个public的service方法,或者一个publi
- 1、cmd指令,进入.svn目录,找到wc.db文件 sqlite 3 打开2、 对 svn源代码目录 右键, clean up, 稍等1至
- 发现问题在一个数据列表中我用了Linq GroupBy 和OrderBy。 排序在本机正常使用,发到测试后排序死活不对,总以为是程序问题。于