使用 SSH.NET 从 ByteArray/MemoryStream 上传 - 文件创建为空(大小为 0KB)

Upload from ByteArray/MemoryStream using SSH.NET - File gets created empty (with size 0KB)

当我第一次下载文件并通过 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);

写入流后,流指针在流的末尾。因此,当您将流传递给 .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,它具有单独的读写指针。