1、引用CoreFtp的方法
1)下载代码引用
下载地址:https://github.com/sparkeh9/CoreFTP/releases
2)使用Nuget引用
在Nuget管理程序中,搜索'CoreFtp
' =》选中然后点击'安装'。
相关文档:VS(Visual Studio)中Nuget的使用
2、连接FTP/S server
using ( var ftpClient = new FtpClient( new FtpClientConfiguration
{
Host = "localhost",
Username = "user",
Password = "password",
Port = 990,
EncryptionType = FtpEncryption.Implicit,
IgnoreCertificateErrors = true
} ) )
{
await ftpClient.LoginAsync();
}
3、从FTP/S server下载文件到本地
using ( var ftpClient = new FtpClient( new FtpClientConfiguration
{
Host = "localhost",
Username = "user",
Password = "password"
} ) )
{
var tempFile = new FileInfo( "C:\\test.png" );
await ftpClient.LoginAsync();
using ( var ftpReadStream = await ftpClient.OpenFileReadStreamAsync( "test.png" ) )
{
using ( var fileWriteStream = tempFile.OpenWrite() )
{
await ftpReadStream.CopyToAsync( fileWriteStream );
}
}
}
4、上传文件到FTP Server
using ( var ftpClient = new FtpClient( new FtpClientConfiguration
{
Host = "localhost",
Username = "user",
Password = "password"
} ) )
{
var fileinfo = new FileInfo( "C:\\test.png" );
await ftpClient.LoginAsync();
using ( var writeStream = await ftpClient.OpenFileWriteStreamAsync( "test.png" ) )
{
var fileReadStream = fileinfo.OpenRead();
await fileReadStream.CopyToAsync( writeStream );
}
}
5、改变FTP Server当前目录、创建目录、删除文件,删除目录
using (var ftpClient = new FtpClient(new FtpClientConfiguration
{
Host = "localhost",
Username = "user",
Password = "password" }))
{
var fileinfo = new FileInfo("C:\\test.png");
await ftpClient.LoginAsync();
//改变目录
await ftpClient.ChangeWorkingDirectoryAsync("work");
//创建目录
await ftpClient.CreateDirectoryAsync("abc");
//删除目录
await ftpClient.DeleteDirectoryAsync("abc");
//删除文件
await ftpClient.DeleteFileAsync("test.png");
}