Dot-Net

使用 SSH.NET 從 ByteArray/MemoryStream 上傳 - 文件創建為空(大小為 0KB)

  • November 10, 2020

當我第一次下載文件並通過 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,它具有單獨的讀寫指針。

引用自:https://stackoverflow.com/questions/35862714