ftp上传文件,报错:System.Net.WebException: 基础连接已经关闭: 服务器提交了协议冲突。
试了 FtpWebRequest 类 和 FluentFTP 客户端库都不行。
更换为 SSH.NET 后可以了。
原因是传统 FTP 客户端会因协议不兼容。FtpWebRequest 和 FluentFTP 是 标准 FTP 客户端,仅支持 FTP 协议,而 ssh.net 是 SSH 客户端库,支持 SFTP 协议。
using Renci.SshNet;
using System;class Program
{static void Main(){// SFTP 服务器信息string server = "your_server_address";int port = 22; // 默认 SFTP 端口是 22string username = "your_username";string password = "your_password";// 本地文件路径和远程目标路径string localFilePath = @"C:\path\to\your\local\file.txt";string remoteFilePath = @"/path/on/remote/server/file.txt";try{// 创建 SFTP 客户端实例using (SftpClient client = new SftpClient(server, port, username, password)){// 连接到 SFTP 服务器client.Connect();// 检查是否成功连接if (client.IsConnected){// 打开本地文件using (var fileStream = System.IO.File.OpenRead(localFilePath)){// 上传文件client.UploadFile(fileStream, remoteFilePath);Console.WriteLine("文件上传成功!");}}else{Console.WriteLine("无法连接到 SFTP 服务器。");}// 断开连接client.Disconnect();}}catch (Exception ex){Console.WriteLine($"发生错误: {ex.Message}");}}
}