这是我的解决方案:
using Tamir.SharpSsh
using Tamir.SharpSsh.jsch
方法代码:
public static bool SftpFile(string ftpAddress, string username, string password, string port, string folderPath, string filename, string separator, string keyFilename, string keyPassword)
{
bool Success = false;
Sftp sftp = null;
try
{
if (filename.Length > 0 && dt != null)
{
int NumberOfConnectionAttempts = 0;
JumpPoint:
try
{
sftp = new Sftp(ftpAddress, username);
sftp.Password = password;
sftp.AddIdentityFile(keyFilename, keyPassword);
sftp.Connect();
sftp.Put(filename + ".csv", (!String.IsNullOrWhiteSpace(folderPath) ? folderPath + "/" : "") + filename + ".csv");
Success = true;
}
catch (Exception ex)
{
Program.DisplayText(" Connection " + NumberOfConnectionAttempts + " failed.\n");
if (NumberOfConnectionAttempts < Program.IntTotalAllowedConnectionAttempts)
{
NumberOfConnectionAttempts++;
Thread.Sleep(1000);
goto JumpPoint;
}
else
{
}
}
}
}
catch (Exception ex)
{
}
finally
{
try { sftp.Close(); }
catch { }
try { sftp = null; }
catch { }
try { GC.Collect(); }
catch { }
}
return Success;
}
使用示例:
string FtpAddress = "??.??.??.??";
string Port = "21";
string Username = "my-username";
string Password = "P455w0rd";
string FolderPath = "folder-name\\";
string Filename = "filename.foo";
string KeyFilename = "keyFilename.bar";
string KeyPassword= "K3yP455w0rd";
if (SftpFile(FtpAddress, Username, Password, Port, FolderPath, Filename, ",", KeyFilename, KeyPassword))
{
}
else
{
}