0 votes
by (260 points)
edited

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
by (147k points)
edited
 
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();
by (260 points)
edited

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

...