SFTP GetStream Failing when Read Offset > 0

0 votes
asked Jul 22, 2011 by Mike Mueller (260 points)
edited Jul 25, 2011

I am using the SFTP library's GetStream/GetRemoteStream to open and read a file from an SFTP server.

Opening the stream and reading from offset 0 works fine. However, when I try to do a subsequent Read calls with a non-zero offset I get an ArgumentException being thrown with an "Invalid offset." message.

Invalid offset. at Rebex.Net.SftpStream.Read(Byte[] buffer, Int32 offset, Int32 count)

Do these methods not support reading from the middle of the remote file? I must read the entire length of the file at once if I want to use the Stream implementation?

Thanks!

Applies to: Rebex SFTP

1 Answer

0 votes
answered Jul 24, 2011 by Lukas Pokorny (102,250 points)
edited Jul 25, 2011
 
Best answer

Are you sure you are calling the Read method correctly? The offset argument is not used to specify a remote offset from which to start reading data. It is an offset to the buffer byte array to which to store the received data. To read data from a non-zero remote file offset, call Seek method on the stream.

For example, if you have a 1024-byte buffer and would like to read a 1024-byte block to it from file offset 40000, you would use the following code:

// create a 1024-byte buffer
byte[] buffer = new byte[1024];

// open a remote file
Stream stream = sftp.GetStream("file.ext", FileMode.Open);

// seek to offset 4000
stream.Seek(40000, SeekOrigin.Begin);

// read 1024 bytes from the current remote file position into the specified buffer
stream.Read(buffer, 0, 1024);

// close the stream
stream.Close();
commented Jul 25, 2011 by Mike Mueller (260 points)
edited Jul 25, 2011

Wow, that's embarrassing... Thanks. We've got some internal tools that work differently, I got confused.

...