CoreFTP .Net Core学习使用
2019-06-18 本文已影响0人
夏天的夏秋天的天
asp.net core ftp文件操作(CoreFTP)学习使用
关于CoreFTP,CoreFTP是完全由C#编写的FTP库,提供FTP功能
官方文档
Nuget引用
在visual studio中直接搜索CoreFtp
即可安装
Nuget简单使用方法
1)创建一个新的类文件CoreFtpOp
//通过构造函数传入配置信息获得ftpClient
_ftpClient = new FtpClient(new FtpClientConfiguration
{
Host = host,
Username = username,
Password = password,
Port = 21,
EncryptionType = FtpEncryption.Implicit,
IgnoreCertificateErrors = true
});
在flpClient中提供了方法
public bool IsAuthenticated { get; }
public bool IsEncrypted { get; }
public bool IsConnected { get; }
public FtpClientConfiguration Configuration { get; }
public string WorkingDirectory { get; }
public ILogger Logger { set; }
public Task ChangeWorkingDirectoryAsync(string directory);
public Task CloseFileDataStreamAsync(CancellationToken ctsToken = default);
public void Configure(FtpClientConfiguration configuration);
public Task CreateDirectoryAsync(string directory);
public Task DeleteDirectoryAsync(string directory);
public Task DeleteFileAsync(string fileName);
public void Dispose();
public Task<long> GetFileSizeAsync(string fileName);
public Task<ReadOnlyCollection<FtpNodeInformation>> ListAllAsync();
public Task<ReadOnlyCollection<FtpNodeInformation>> ListDirectoriesAsync();
public Task<ReadOnlyCollection<FtpNodeInformation>> ListFilesAsync();
public Task LoginAsync();
public Task LogOutAsync();
public Task<Stream> OpenFileReadStreamAsync(string fileName);
public Task<Stream> OpenFileWriteStreamAsync(string fileName);
public Task RenameAsync(string from, string to);
public Task<FtpResponse> SendCommandAsync(FtpCommandEnvelope envelope,
CancellationToken token = default);
public Task<FtpResponse> SendCommandAsync(string command, CancellationToken
token = default);
public Task<FtpResponse> SetClientName(string clientName);
public Task SetTransferMode(FtpTransferMode transferMode, char secondType =
'\0');
在使用之前我们得先连接到ftp服务器
使用LoginAsync();进行登录。
登录状态可通过IsConnected判断
从本地上传文件到Ftp服务器
public async Task<string> upload(string path, string sourcePath)
{
try
{
//获取本地文件信息
var fileinfo = new FileInfo(sourcePath);
await _ftpClient.LoginAsync();
//判断连接状态
if (!_ftpClient.IsConnected)
{
return "could not connect ftp";
}
using (var writeStream = await
//ftp服务器
_ftpClient.OpenFileWriteStreamAsync(path))
{
var fileReadStream = fileinfo.OpenRead();
//写入
await fileReadStream.CopyToAsync(writeStream);
return "success";
}
}
catch (Exception e)
{
return e.Message;
}
finally
{
_ftpClient.Dispose();
}
}
还有其他得方法
//获得当前目录
var currentdir = _ftpClient.WorkingDirectory;
//改变当前目录
_ftpClient.ChangeWorkingDirectoryAsync(@"/home");
//获取目录下所有
_ftpClient.ListAllAsync();
//获取目录下目录
_ftpClient.ListDirectoriesAsync();
//获取目录下文件
_ftpClient.ListFilesAsync();
//等等其他方法
其它方法可在官方文档上查看
继续学习~~~~~