需要下載 的包:Core.Renci.SshNet
下載依賴包的時候需要注意版本,高版本的.net環境不支持會用不了,我用的.net5,所以下載的2021.10.2
功能的核心式創建一個SftpClient,并傳入所需要的參數:遠程IP地址,端口號,遠程端用戶名和密碼。示例代碼如下:
var connectionInfo= new ConnectionInfo(address, username, new PasswordAuthenticationMethod(username, password) ) ;using (var client = new SftpClient(connectionInfo)){client.Connect();if (client.IsConnected){var remoteFiles = client.ListDirectory(sourceFolder).Where(f=>!f.IsDirectory&&!f.Name.StartsWith("."));//遠程端文件夾地址foreach (var file in remoteFiles) {string remotePath = $"{sourceFolder}/{file.Name}";using (var fs = File.Open(localPath,FileMode.Create))//localPath:本地要存放的地址{client.DownloadFile(remotePath, fs);} }}}}
}