简体   繁体   中英

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

I would like to download a file from SFTP using the SSH.NET library. However, I would like this file to be received in Byte array. Thus, this file must be stored in memory .

Here's how I do it

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

However this method does not work: indeed, by writing it on the disk to test it, it is corrupted.

Your code is imo more or less correct. The only problem is that, in VB.NET, the New Byte(X) does allocate an array one byte longer than you want: 0..X (not 1..X or 0..X-1 as you might have expected).

So if you then save the complete array (eg by File.WriteAllBytes ) and not only stream.Length bytes, the file will be one byte larger, with an additional trailing NULL byte.

This is correct:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM