using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Renci.SshNet;
namespace TestSFTP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class sFtpHelper
{
public static int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + fileName;
string remoteFileName = filePath+ "/"+ fileName;
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.Open(localFileName,FileMode.OpenOrCreate))
{
sftp.DownloadFile(remoteFileName, file);
}
sftp.Disconnect();
Console.WriteLine("下载文件成功,文件路径:"+localFileName);
return 0;
}
}
catch (Exception e)
{
MessageBox.Show("下载失败,原因:"+e.Message );
return -2;
}
}
public static int UploadFtp(string filePath, string localPath, string filename, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + filename;
string remoteFileName = "/"+filePath+"/"+filename;
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.OpenWrite(localFileName))
{
sftp.UploadFile(file, remoteFileName);
}
sftp.Disconnect();
Console.WriteLine("上传文件成功,文件路径:"+localFileName);
return 0;
}
}
catch (Exception ex)
{
Console.WriteLine("上传失败,原因:"+ex.Message );
return -2;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string sftpHost = "sftp.xxx.com";
string sFile= "aaa.txt";
sFtpHelper.DownloadFtp("/upload/weblicense/dd", "d:\\",sFile , sftpHost, "22", "username222", "pwd123");
}
}
}
完整实例(包含显示下载进度):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Renci.SshNet;
using System.Threading.Tasks;
using Renci.SshNet.Sftp;
using System.Diagnostics;
namespace TestSFTP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + fileName;
string remoteFileName = filePath + "/" + fileName;
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.Open(localFileName, FileMode.OpenOrCreate))
{
sftp.DownloadFile(remoteFileName, file);
//sftp.BeginDownloadFile(
}
sftp.Disconnect();
display("下载文件成功,文件路径:" + localFileName);
return 0;
}
}
catch (Exception e)
{
display("下载失败,原因:" + e.Message);
return -2;
}
}
public int UploadFtp(string filePath, string localPath, string filename, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + filename;
string remoteFileName = "/" + filePath + "/" + filename;
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.OpenWrite(localFileName))
{
sftp.UploadFile(file, remoteFileName);
}
sftp.Disconnect();
Console.WriteLine("上传文件成功,文件路径:" + localFileName);
return 0;
}
}
catch (Exception ex)
{
Console.WriteLine("上传失败,原因:" + ex.Message);
return -2;
}
}
public int DownloadFtpWithProgress(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + fileName;
string remoteFileName = filePath + "/" + fileName;
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
bool IsExists = sftp.Exists(remoteFileName);
if (!IsExists)
{
return 0;
}
//get the attributes of the file (namely the size)
SftpFileAttributes att = sftp.GetAttributes(remoteFileName);
long fileSize = att.Size;
//download the file as a memory stream and convert to a file stream
using (MemoryStream ms = new MemoryStream())
{
IAsyncResult asyncr = sftp.BeginDownloadFile(remoteFileName, ms);
SftpDownloadAsyncResult sftpAsyncr = (SftpDownloadAsyncResult)asyncr;
while (!sftpAsyncr.IsCompleted)
{
int pct = (int)(((double)sftpAsyncr.DownloadedBytes / fileSize) * 100);
Debug.Print("Downloaded {0} of {1} ({2}%).", sftpAsyncr.DownloadedBytes, fileSize, pct);
Text=string.Format ("Downloaded {0} of {1} ({2}%).", sftpAsyncr.DownloadedBytes, fileSize, pct);
pgbMain.Value = pct;//pgbMain is the progressBar ui control
Application.DoEvents();
}
sftp.EndDownloadFile(asyncr);
//write the memory stream to the file stream
var fs = File.Open(localFileName, FileMode.Create);
ms.WriteTo(fs);
fs.Close();
ms.Close();
}
sftp.Disconnect();
display("下载文件成功,文件路径:" + localFileName);
return 0;
}
}
catch (Exception e)
{
display("下载失败,原因:" + e.Message);
return -2;
}
}
void display(string s)
{
richTextBox1.AppendText(s + "\r\n");
}
private void button1_Click(object sender, EventArgs e)
{
string sftpHost = "sftp.xxx.com";
string sFile = "SWMM7ActiveProductDevelopment-GuangshuWang.mem";
DownloadFtpWithProgress("/upload/weblicense/swmm7000", "d:\\", sFile, sftpHost, "22", "username", "pwd...");
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
界面代码:
namespace TestSFTP
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.pgbMain = new System.Windows.Forms.ProgressBar();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(293, 23);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(241, 67);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(76, 151);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(639, 244);
this.richTextBox1.TabIndex = 1;
this.richTextBox1.Text = "";
//
// pgbMain
//
this.pgbMain.Location = new System.Drawing.Point(106, 107);
this.pgbMain.Name = "pgbMain";
this.pgbMain.Size = new System.Drawing.Size(609, 23);
this.pgbMain.TabIndex = 2;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.pgbMain);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.ProgressBar pgbMain;
}
}
SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism.
【从nuget中下载SSH.NET】
摘自 http://www.cnblogs.com/cbread/p/6202069.html