using Renci.SshNet;
using System;
class Program
{
static void Main(string[] args)
{
string host = "your.sftp.server.com";
string username = "yourUsername";
string password = "yourPassword";
string remotePath = "/remote/path/";
string localPath = @"C:\local\path\file.txt";
using (var client = new SftpClient(host, username, password))
{
try
{
client.Connect();
// Upload a file to the SFTP server
using (var fileStream = System.IO.File.OpenRead(localPath))
{
client.UploadFile(fileStream, remotePath + "uploaded-file.txt");
}
Console.WriteLine("File uploaded successfully.");
// Download a file from the SFTP server
using (var fileStream = new System.IO.FileStream(@"C:\local\path\downloaded-file.txt", System.IO.FileMode.Create))
{
client.DownloadFile(remotePath + "file-to-download.txt", fileStream);
}
Console.WriteLine("File downloaded successfully.");
client.Disconnect();
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
}
引用命名空间:代码中使用了 Renci.SshNet 命名空间,这是一个用于处理 SSH 和 SFTP 操作的库。你需要通过 NuGet 安装此包(Install-Package Renci.SshNet)。
连接到 SFTP 服务器:
SftpClient 类创建一个 SFTP 客户端实例,并提供主机地址、用户名和密码。Connect() 方法连接到 SFTP 服务器。上传文件:
UploadFile() 方法将本地文件上传到远程服务器。需要提供文件流和远程路径。下载文件:
DownloadFile() 方法从远程服务器下载文件。同样需要提供文件流和远程路径。异常处理:
try-catch 块捕获并处理可能发生的异常,例如连接失败或文件操作错误。断开连接:
Disconnect() 方法断开与 SFTP 服务器的连接。确保你已经安装了 Renci.SshNet 库,并根据实际情况修改主机地址、用户名、密码以及文件路径。
上一篇:c# sm4加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站