3

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.

3
  • I'm not sure whether this is the only issue but how do you create an array? Do you specify the length or the upper bound? Commented Aug 5, 2019 at 1:12
  • Are you sure the stream from client.OpenRead("/www/Server.exe") is valid? Commented Aug 5, 2019 at 1:51
  • 1
    How corrupted? Are some bytes modified? Is the file truncated? + Why do you even need byte array? Isn't Stream you get from OpenRead enough for most purposes? Commented Aug 5, 2019 at 7:24

1 Answer 1

3

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 (e.g. 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) {}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for spending time looking at my code! Yes indeed, I was convinced that my problem was a mishandling of SSH.NET, not the byte array ... I understand, the problem is finally quite sensitive, especially when handling a byte array. Anyway, thank you again for your help, you explain well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.