Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# sftp

作者:血之メ狂霸   发布日期:2026-05-02   浏览:68

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);
            }
        }
    }
}

解释说明

  1. 引用命名空间:代码中使用了 Renci.SshNet 命名空间,这是一个用于处理 SSH 和 SFTP 操作的库。你需要通过 NuGet 安装此包(Install-Package Renci.SshNet)。

  2. 连接到 SFTP 服务器

    • 使用 SftpClient 类创建一个 SFTP 客户端实例,并提供主机地址、用户名和密码。
    • 调用 Connect() 方法连接到 SFTP 服务器。
  3. 上传文件

    • 使用 UploadFile() 方法将本地文件上传到远程服务器。需要提供文件流和远程路径。
  4. 下载文件

    • 使用 DownloadFile() 方法从远程服务器下载文件。同样需要提供文件流和远程路径。
  5. 异常处理

    • 使用 try-catch 块捕获并处理可能发生的异常,例如连接失败或文件操作错误。
  6. 断开连接

    • 完成操作后调用 Disconnect() 方法断开与 SFTP 服务器的连接。

确保你已经安装了 Renci.SshNet 库,并根据实际情况修改主机地址、用户名、密码以及文件路径。

上一篇:c# sm4加密

下一篇:c# string 转datetime

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站