您的代码不访问任何服务器。它不使用 FTP 或 SFTP。它适用于本地文件。
无论如何,如果 FTP 和 SFTP 是您唯一可用的接口,则无法直接将文件从 FTP 复制到 SFTP 服务器。
您必须从 FTP 服务器下载文件,然后将它们上传到 SFTP 服务器。
您可以将下载的文件直接流式上传,避免将文件存储到临时本地文件中。
如果您想使用内置的 .NET FTP 实现 (WebClient/FtpWebRequest) 和本机 .NET SFTP 库(如 SSH.NET),您可以执行以下操作:
var ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential("ftpuser", "ftppass");
var ftpUrl = "ftp://ftp.example.com/ftp/path/file.csv";
using (var ftpStream = ftpClient.OpenRead(ftpUrl))
using (var sftpClient = new SftpClient("sftp.example.com", "sftpuser", "sftppass"))
{
sftpClient.UploadFile(ftpStream, "/sftp/path/file.csv");
}
移动已处理的文件:
FtpWebRequest ftpRequest = new FtpWebRequest(ftpUrl);
ftpRequest.Method = WebRequestMethods.Ftp.Rename;
ftpRequest.RenameTo = "/ftp/path/processed/file.csv";
ftpRequest.GetResponse();
如果是这两个 SFTP 服务器,使用我的WinSCP .NET assembly 会更容易一些。什么不是本机 .NET 库,但它是 can be used from SSIS。使用 WinSCP,代码如下:
// Setup session options
SessionOptions sftpSessionOptions1 = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "sftp1.example.com",
UserName = "username1",
Password = "password",
};
SessionOptions sftpSessionOptions2 = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "sftp2.example.com",
UserName = "username2",
Password = "password",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};
using (Session sftpSession1 = new Session())
using (Session sftpSession2 = new Session())
{
// Connect to SFTP 1
ftpSession1.Open(sftpSessionOptions1);
// Get list of files in the FTP directory
string sftpRemoteDir1 = "/ftp/remote/path";
RemoteDirectoryInfo dirInfo = sftpSession1.ListDirectory(sftpRemoteDir1);
// Select the most recent file
RemoteFileInfo latest =
dirInfo.Files
.Where(file => !file.IsDirectory)
.OrderByDescending(file => file.LastWriteTime)
.First();
// Connect to SFTP
sftpSession2.Open(sftpSessionOptions2);
string sftpRemoteDir2 = "/sftp/remote/path";
string sftpRemotePath2 = RemotePath.Combine(sftpRemoteDir2, latest.Name);
// Transfer from SFTP 1 to SFTP 2
using (Stream downloadStream = sftpSession1.GetFile(latest.FullName))
{
sftpSession2.PutFile(downloadStream, sftpRemotePath2);
}
// Move the source file to the "processed" folder
string processedDir = "/sftp/remote/path/processed";
string processedPath = RemotePath.Combine(processedDir, latest.Name);
ftpSession.MoveFile(latest.FullName, processedPath);
}
未经测试。需要 WinSCP 5.19 或更高版本。