.net - 使用 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..X
或0..X-1
您可能期望的那样)。
因此,如果您随后保存完整的数组(例如 by File.WriteAllBytes
)而不仅仅是stream.Length
字节,则文件将大一个字节,并带有一个额外的尾随 NULL 字节。
这是对的:
Dim fileData As Byte() = New Byte(streamLength - 1) {}
推荐阅读
- python - 为什么python默认启用断言
- oracle - 在 oracle sql 中从子节点中查找根父节点
- mysql - Sql:加入2个没有公共字段的表
- javascript - 以角度单击按钮后未触发 ngOnDestroy
- sails.js - 尝试在模型上实施关系后,Sails Lift 停止工作
- mysql - 如何从 Python 3 将值插入 Mysql 表中的 DATE 列
- javascript - xml中的自闭标签空间问题 - Cheerio
- nginx - Nginx 与 openssl 构建错误 CentOS 7 -“基本名称:缺少操作数”
- c++ - 为什么在向量包围的向量上使用 .pushback 时出现重叠错误
- docker - 在代码中检索当前环境(Kotlin、Docker)