用NuGet下載WinSCP .Net Assembly,Version:5.7.4
官方網頁
原始碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinSCP;
namespace FTP_download_and_upload_with_WinSCP
{
class Program
{
static string ftpUploadUrl = "IP或domain"; //不可以有ftp:\
static string ftpAccount = "Ftp帳號";
static string ftpPassword = "Ftp密碼";
static string localPath = @"D:\temp\";
static string remotePath = "/work/";
static void Main(string[] args)
{
Download();
Upload();
}
private static void Upload()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = ftpUploadUrl,
UserName = ftpAccount,
Password = ftpPassword,
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.PutFiles(localPath + "*", remotePath, true, transferOptions); //*表示全部檔案
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
}
session.Close();
}
}
catch (Exception e)
{
throw e;
}
}
private static void Download()
{
try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = ftpUploadUrl,
UserName = ftpAccount,
Password = ftpPassword,
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult = session.GetFiles(remotePath + "*", localPath, false, transferOptions);//*表示全部檔案
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded", transfer.FileName);
}
session.Close();
}
}
catch (Exception e)
{
throw e;
}
}
}
}