You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SSH.NET上传文件至SFTP报错求助:无法确定文件状态等问题

SSH.NET上传文件至SFTP的问题排查与解决

问题场景

  • 尝试用ScpClient上传文件,代码如下:
using (var client = new ScpClient(host, port, user, password))
{
    client.Connect();

    FileInfo file = new FileInfo(fileFullName);
    string fileName = Path.GetFileName(fileFullName);

    client.Upload(file, uploadFolder + fileName);
}

连接正常,但调用Upload时抛出错误:Renci.SshNet.Common.ScpException: Receive file existence status cannot be determined,已确认目标路径、权限、本地文件均无问题,仅需上传新文件无需覆盖。

  • 改用SftpClient尝试,代码如下:
using (var client = new SftpClient(host, port, user, password))
{
    client.Connect();

    using (var fs = File.OpenRead(fileFullName))
    {
        client.UploadFile(fs, uploadFolder, true);
    }
}

调用UploadFile时抛出错误:System.Exception: 'General failure '

解决办法

针对ScpClient的报错

该错误多因SCP协议检查目标文件状态时,服务器响应不符合SSH.NET预期,可尝试:

  1. 确认目标路径格式:保证uploadFolder与文件名拼接后是完整文件路径,若服务器为Linux/Unix系统,路径分隔符用/;Windows系统用\。
  2. 切换至SftpClient:ScpClient缺乏跳过文件检查的直接参数,SftpClient的上传逻辑更灵活可靠。

针对SftpClient的报错

核心问题是UploadFile的第二个参数需传入完整目标文件路径(含文件名),而非仅文件夹路径,修正后代码如下:

using (var client = new SftpClient(host, port, user, password))
{
    client.Connect();

    // 确保目标文件夹存在,不存在则创建
    if (!client.Exists(uploadFolder))
    {
        client.CreateDirectory(uploadFolder);
    }

    string targetFilePath = Path.Combine(uploadFolder, Path.GetFileName(fileFullName));
    // 根据服务器系统替换路径分隔符
    targetFilePath = targetFilePath.Replace('\\', '/');

    using (var fs = File.OpenRead(fileFullName))
    {
        // 第三个参数设为false,避免覆盖已存在文件
        client.UploadFile(fs, targetFilePath, false);
    }
}

额外注意事项

  • 根据服务器操作系统调整路径分隔符,避免格式错误。
  • 上传前检查并创建目标文件夹,防止因文件夹不存在导致失败。
  • 若仍有问题,可开启错误日志排查细节:
client.ErrorOccurred += (sender, e) => Console.WriteLine($"Error: {e.Exception.Message}");
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(30);

内容的提问来源于stack exchange,提问作者Rinfra90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:27:16