Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 429
Peter PitLock Avatar asked Mar 08 '16 08:03

Peter PitLock


1 Answers

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)

An alternative is to use SSH.NET PipeStream, which has separate read and write pointers.

like image 129
Martin Prikryl Avatar answered Nov 11 '22 21:11

Martin Prikryl