使用 SSH.NET 从 ByteArray/MemoryStream 上传 - 文件创建为空(大小为 0KB)
- 作者: -大宏哥
- 来源: 51数据库
- 2022-12-15
问题描述
当我第一次下载文件并通过 SSH.NET 上传时,一切正常.
When I first download a file and upload it via SSH.NET, all works fine.
client.DownloadFile(url, x)
Using fs= System.IO.File.OpenRead(x)
sFtpClient.UploadFile(fs, fn, True)
End Using
但是我现在必须(不是下载文件)而是上传文件流:
However I must now (not download the file) but upload a stream of the file:
Dim ba As Byte() = client.DownloadData(url) Dim stream As New MemoryStream() stream.Write(ba, 0, ba.Length) sFtpClient.UploadFile(stream, fn, True)
发生的事情是 UploadFile 方法认为它成功了,但在实际的 FTP 上,创建的文件大小为 0KB.
What is happening is that the UploadFile method thinks it succeeded, but on the actual FTP, the file is created with size 0KB.
请问我做错了什么?我也尝试添加缓冲区大小,但没有用.
What am I doing wrong please? I tried adding the buffer size too, but it did not work.
我在网上找到了代码.我应该做这样的事情吗:
I found code on the web. Should I be doing something like this:
client.ChangeDirectory(pFileFolder); client.Create(pFileName); client.AppendAllText(pFileName, pContents);
推荐答案
写入流后,流指针位于流的末尾.因此,当您将流传递给 .UploadFile 时,它会从指针(位于末尾)到末尾读取流.因此,什么都没有写.并且不会发出任何错误,因为一切都按设计运行.
After writing to the stream, the stream pointer is at the end of the stream. So when you pass the stream to the .UploadFile, it reads the stream from the pointer (which is at the end) to the end. Hence, nothing is written. And no error is issued, because everything behaves as designed.
在将流传递给 .UploadFile 之前,您需要将指针重置为开头:
You need to reset the pointer to the beginning, before passing the stream to the .UploadFile:
Dim ba As Byte() = client.DownloadData(url) Dim stream As New MemoryStream() stream.Write(ba, 0, ba.Length) ' Reset the pointer stream.Position = 0 sFtpClient.UploadFile(stream, fn, True)
另一种方法是使用 SSH.NET PipeStream,它具有单独的读写指针.
An alternative is to use SSH.NET PipeStream, which has separate read and write pointers.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
