【问题标题】:Upload from ByteArray/MemoryStream using SSH.NET - File gets created empty (with size 0KB)使用 SSH.NET 从 ByteArray/MemoryStream 上传 - 文件创建为空(大小为 0KB)
【发布时间】:2020-11-10 18:49:25
【问题描述】:

当我第一次下载文件并通过 SSH.NET 上传时,一切正常。

client.DownloadFile(url, x)
Using fs= System.IO.File.OpenRead(x)
    sFtpClient.UploadFile(fs, fn, True)
End Using

但是我现在必须(不是下载文件)而是上传文件流:

Dim ba As Byte() = client.DownloadData(url)
Dim stream As New MemoryStream()
stream.Write(ba, 0, ba.Length)
sFtpClient.UploadFile(stream, fn, True)

发生的情况是UploadFile 方法认为它成功了,但在实际的 FTP 上,创建的文件大小为 0KB。

请问我做错了什么?我也尝试添加缓冲区大小,但没有奏效。

我在网上找到了代码。我应该这样做吗:

client.ChangeDirectory(pFileFolder);
client.Create(pFileName);
client.AppendAllText(pFileName, pContents);

【问题讨论】:

    标签: .net vb.net stream sftp ssh.net


    【解决方案1】:

    写入流后,流指针位于流的末尾。因此,当您将流传递给.UploadFile 时,它会从指针(位于末尾)到末尾读取流。因此,什么都没有写。并且不会发出任何错误,因为一切都按设计运行。

    在将流传递给.UploadFile之前,您需要将指针重置为开头:

    Dim ba As Byte() = client.DownloadData(url)
    Dim stream As New MemoryStream()
    stream.Write(ba, 0, ba.Length)
    ' Reset the pointer
    stream.Position = 0
    sFtpClient.UploadFile(stream, fn, True)
    

    另一种方法是使用 SSH.NET PipeStream,它具有单独的读写指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2021-05-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多