首页 > 解决方案 > 使用 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

但是这种方法不起作用:实际上,通过将其写入磁盘进行测试,它已损坏。

标签: .netvb.netdownloadsftpssh.net

解决方案


您的代码或多或少是正确的。唯一的问题是,在 VB.NET 中,New Byte(X)确实分配了一个比您想要的长一个字节的数组:(0..X不是1..X0..X-1您可能期望的那样)。

因此,如果您随后保存完整的数组(例如 by File.WriteAllBytes)而不仅仅是stream.Length字节,则文件将大一个字节,并带有一个额外的尾随 NULL 字节。

这是对的:

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

推荐阅读