簡體   English   中英

使用 SSH.NET (VB.NET) 將文件下載到字節數組

[英]Download file to byte array using SSH.NET (VB.NET)

我想使用 SSH.NET 庫從 SFTP 下載文件。 但是,我希望在Byte數組中接收此文件。 因此,這個文件必須存儲在內存中

這是我的方法

Sub Main()
   Dim client As SftpClient = New SftpClient(hostname, username, password)
   client.Connect()
   Using b As System.IO.Stream = client.OpenRead("/www/Server.exe")
        Dim data() As Byte = GetStreamAsByteArray(b)
   End Using
End Sub

Public Shared Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
    Dim streamLength As Integer = Convert.ToInt32(stream.Length)

    Dim fileData As Byte() = New Byte(streamLength) {}

    ' Read the file into a byte array
    stream.Read(fileData, 0, streamLength)
    stream.Flush()
    stream.Close()

    Return fileData
End Function

但是這種方法不起作用:實際上,通過將其寫入磁盤進行測試,它已損壞。

您的代碼或多或少是正確的。 唯一的問題是,在 VB.NET 中, New Byte(X)確實分配了一個比您想要的長一個字節的數組: 0..X (不是您可能期望的1..X0..X-1 )。

因此,如果您隨后保存完整的數組(例如通過File.WriteAllBytes )而不僅僅是stream.Length字節,則文件將大一個字節,並帶有一個附加的尾隨 NULL 字節。

這是對的:

Dim fileData As Byte() = New Byte(streamLength - 1) {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM