Upload from ByteArray/MemoryStream using SSH.NET - File gets created with size 0KB

怎甘沉沦 提交于 2019-12-18 04:52:38

问题


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)

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);

回答1:


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.

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)


来源:https://stackoverflow.com/questions/35862714/upload-from-bytearray-memorystream-using-ssh-net-file-gets-created-with-size-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!