SftpFileStream path question
I am connecting to a 3rd party SFTP server. I need to download all files in a folder with download resume functionality. After getting a listing of files in the current folder from the remote server, I am unable to create a SftpFileStream object for them using SftpClient.OpenRead. When I past SftpFile.Name or SftpFile.FullName as the path I get "Folder not found" error. But it is there or it wouldn't be in the list of files from SftpClient.ListDirectory. Am I not understanding the correct use of path in OpenRead?
Code from Visual Studio 2015 console app. SSH.NET from NuGet.
Error is on line: Dim sffsRemoteFile As SftpFileStream = sftpClient.OpenRead(sfFile.Name)
Message: Folder not found: LOG_us_prin_multi_replica_2016091806.SQB
Stack Trace: at Renci.SshNet.Sftp.SftpSession.RequestOpen(String path, Flags flags, Boolean nullOnError) at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize, Boolean useAsync) at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize) at Renci.SshNet.SftpClient.OpenRead(String path) at SSHFTP.SSHFTP.Download_Many_With_Resume(String pServer, String pUser, String pPass, String pRmPath, String pLcPath, Int32 pPort, Int32 pBlock, Int32 pTimeout) in C:\Users\Will\Documents\Visual Studio 2015\Projects\SSHFTP\SSHFTP\SSHFTP.vb:line 318
Private Sub Download_Many_With_Resume(pServer As String, pUser As String, pPass As String, pRmPath As String, pLcPath As String, pPort As Integer, pBlock As Integer, pTimeout As Integer)
Dim boolErrorLogged As Boolean = False
Dim strStatusMsg As String = "Init"
Dim strTempFileSuffix As String = ".filepart"
Dim sftpClient As Renci.SshNet.SftpClient = New Renci.SshNet.SftpClient(pServer, pPort, pUser, pPass)
Try '// Main Try
sftpClient.BufferSize = pBlock
If (pTimeout > 0) Then
sftpClient.KeepAliveInterval = New TimeSpan(0, 0, pTimeout)
End If '// End If (mintTimeout > 0) Then
sftpClient.Connect()
sftpClient.ChangeDirectory(pRmPath) '// In test case /prinftpuser/dbreplication/Logs/
'// List all files and folders in the remote path...WRG
Dim lofListing As List(Of SftpFile) = sftpClient.ListDirectory(".").ToList()
If lofListing IsNot Nothing AndAlso lofListing.Count() > 2 Then
'// Filter the listing for files based on dos wildcard from command line...WRG
Dim lofFilteredList As List(Of SftpFile) = lofListing.FindAll(AddressOf FilterByMask)
For Each sfFile As SftpFile In lofFilteredList
Dim strLocalTempFile As String = pLcPath + sfFile.Name + strTempFileSuffix
Dim lngOffset As Long = 0
If File.Exists(strLocalTempFile) Then
'// Resume a past download...WRG
lngOffset = My.Computer.FileSystem.GetFileInfo(strLocalTempFile).Length
End If '// End If File.Exists(strLocalTempFile) Then
If Not File.Exists(pLcPath + sfFile.Name) Then
Dim sLocalFile As Stream = File.Open(strLocalTempFile, FileMode.OpenOrCreate, FileAccess.Write)
strStatusMsg = "File : " + sfFile.FullName
Try '// Write File Try
Dim intReadPos As Integer = 0
Dim lngByteCount As Long = lngOffset
Dim bFileChunk(mintBlockSize) As Byte
Dim sffsRemoteFile As SftpFileStream = sftpClient.OpenRead(sfFile.Name)
'// Note that all code past this point is untested as I can't get OpenRead to give me a stream...WRG
'// For a resume jump the stream to the point we need to resume from...WRG
If lngOffset > 0 Then
sffsRemoteFile.Position = lngOffset
End If
Do '// Main read loop...WRG
If sffsRemoteFile.CanRead Then
intReadPos = sffsRemoteFile.Read(bFileChunk, 0, bFileChunk.Length)
sLocalFile.Write(bFileChunk, 0, intReadPos)
Else
intReadPos = 0
End If
lngByteCount += intReadPos
Loop Until intReadPos = 0 '// End Main read loop...WRG
sffsRemoteFile.Close()
'// Check to see if the whole file been downloaded...WRG
If lngByteCount <> sfFile.Attributes.Size Then
'// Byte counts don't match, download is not complete...WRG
boolErrorLogged = True
strStatusMsg = "Partial write (" + sfFile.Name + ")"
Else
'// All is well...WRG
strStatusMsg = "File write (" + sfFile.Name + ") completed"
End If
Catch ex As Exception
boolErrorLogged = True
strStatusMsg += " write file error :" + ex.Message
Finally '// Finally Write File Try
sLocalFile.Flush()
sLocalFile.Close()
sLocalFile = Nothing
End Try '// End Write File Try
If File.Exists(strLocalTempFile) And Not boolErrorLogged Then
'// Set the file's modified and last access timestamp. Leave create alone to track download timestamp...WRG
File.SetLastAccessTime(strLocalTempFile, sfFile.Attributes.LastAccessTime)
File.SetLastWriteTime(strLocalTempFile, sfFile.Attributes.LastWriteTime)
'// Rename the now completed download...WRG
My.Computer.FileSystem.RenameFile(strLocalTempFile, sfFile.Name)
End If '// End If File.Exists(strLocalTempFile) And Not boolErrorLogged Then
Else
strStatusMsg = "File already exists, can not download " + sfFile.Name
End If '// End If Not File.Exists(pLcPath + sfFile.Name) Then
System.Console.WriteLine(strStatusMsg)
strStatusMsg = ""
Next '// End For Each sfFile As SftpFile In lofFilteredList
Else
boolErrorLogged = True
strStatusMsg = "File not found, " + pRmPath + mstrFileMask
End If '// End If lofListing IsNot Nothing AndAlso lofListing.Count() > 2 Then
Catch ex As Exception
boolErrorLogged = True
strStatusMsg = "Download error :" + ex.Message + " " + mstrFileMask
Finally '// Main Try
If sftpClient.IsConnected Then
sftpClient.Disconnect()
End If '// End If sftpClient.IsConnected Then
sftpClient.Dispose()
sftpClient = Nothing
'// Display any final messages...WRG
System.Console.WriteLine(strStatusMsg)
End Try '// Main Try
End Sub
Oh, and if I use SftpFile.FullName as the path rather than SftpFile.Name, then I get the following error message:
Folder not found: \\ustr\ftp\customerfiles\ftpfiles\prin\dbreplication\Logs\LOG_us_prin_multi_replica_2016091806.SQB
As we're using FullName.Substring(FullName.LastIndexOf('/') + 1) to get value of the Name, I can't see how FullName can include backslashes, while Name still includes only the file name part.
Also your code snippet does not ever write the "Folder not found" error. Please include a complete example, and the output produced by it.
That's just it, FullName doesn't have backslashes, according to the watch it has "/prinftpuser/dbreplication/Logs/LOG_us_prin_multi_replica_2016091806.SQB". The backslashes don't show up until the Exception object's message returns them. I was confused by the output as well, it made no sense that I pass in "/prinftpuser/dbreplication/Logs/LOG_us_prin_multi_replica_2016091806.SQB" and the exception message returns "\ustr\ftp\customerfiles\ftpfiles\prin\dbreplication\Logs\LOG_us_prin_multi_replica_2016091806.SQB".
The only code I have is my testing project and it's very messy because I'm in the middle of learning the ssh.net library. Let me clean it up and I'll post it later.
The path in the exception comes from the SSH server. I don't have much time today, but I think the problem comes from the fact that you pass a relative path (the filename relative to the working directory). It appears as if OpenRead (and just about any method in SftpClient that returns a SftpFileStream) expects an absolute path.
I'll verify this later this week, and - when confirmed - fix this issue as soon as possible.
Thank you for looking at this.
It was easier for me to put together a new test project than clean up my other one, so here is a complete example. Also, I did it in C# as most people don't like to look a VB now days. This lead to an interesting find. While it gives the same error, the message is a little different in C#, it has the relative path in the message but still fails to find it. Again, that doesn't track because the path comes from a list generated by ListDirectory so they must be there to be in the list. I think you are correct and it's an issue with absolute path vs relative path. The message in VB makes it a little easier to see the issue but I think it's the same issue for both C# and VB.
using Renci.SshNet.Sftp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace tester {
class Program {
static void Main(string[] args) {
string strServer = "xxxx";
string strUser = "xxxx";
string strPass = "xxxx";
string strRmPath = "./dbreplication/Logs/";
string strLcPath = "C:\\Temp\\test\\";
string strStatusMsg = "Init";
int intPort = 22;
UInt32 intBlock = 8192;
Renci.SshNet.SftpClient sftpClient = new Renci.SshNet.SftpClient(strServer, intPort, strUser, strPass);
try { // Main Try
sftpClient.Connect();
List<SftpFile> lofListing = sftpClient.ListDirectory(strRmPath).ToList();
foreach (SftpFile sfFile in lofListing) {
if ((!sfFile.IsDirectory) && (sfFile.IsRegularFile)) {
System.Console.WriteLine("Remote File: " + sfFile.FullName);
Stream sLocalFile = File.Open(strLcPath + sfFile.Name, FileMode.OpenOrCreate, FileAccess.Write);
try { // Write File Try
if (sLocalFile.Length > 0) {
sLocalFile.Position = sLocalFile.Length;
}
if (sfFile.Attributes.Size > sLocalFile.Length) {
int intReadPos = 0;
long lngByteCount = sLocalFile.Length;
byte[] bFileChunk = new byte[intBlock + 1];
SftpFileStream sffsRemoteFile = sftpClient.OpenRead(strRmPath + sfFile.Name);
try { // Read Remote File Try
if (lngByteCount > 0) {
sffsRemoteFile.Position = lngByteCount;
}
do { // Main read loop...WRG
if (sffsRemoteFile.CanRead) {
intReadPos = sffsRemoteFile.Read(bFileChunk, 0, bFileChunk.Length);
sLocalFile.Write(bFileChunk, 0, intReadPos);
} else {
intReadPos = 0;
}
lngByteCount += intReadPos;
} while (intReadPos > 0); // End Main read loop...WRG
} catch (Exception ex) { // Catch Read Remote File Try
System.Console.WriteLine("Read remote file error: " + ex.Message);
} finally { // Finally Read Remote File Try
sffsRemoteFile.Close();
sffsRemoteFile.Dispose();
sffsRemoteFile = null;
} // End Read Remote File Try
if (lngByteCount != sfFile.Attributes.Size) {
strStatusMsg = "Partial write (" + sfFile.Name + ")";
} else {
strStatusMsg = "File write (" + sfFile.Name + ") completed";
} // End if (lngByteCount != sfFile.Attributes.Size)
} else {
strStatusMsg = "Already local.";
} // End if (sfFile.Attributes.Size > sLocalFile.Length)
System.Console.WriteLine(strStatusMsg);
} catch (Exception ex) { // Catch Write File Try
System.Console.WriteLine("Write file error: " + ex.Message);
} finally { // Finally Write File Try
sLocalFile.Flush();
sLocalFile.Close();
sLocalFile.Dispose();
sLocalFile = null;
} // End Write File Try
} // End if (!sfFile.IsDirectory)
} // End foreach (SftpFile sfFile in lofListing)
} catch (Exception ex) { // Catch Main Try
strStatusMsg = "Download error :" + ex.Message;
} finally { // Finally Main Try
if (sftpClient.IsConnected) {
sftpClient.Disconnect();
}
sftpClient.Dispose();
sftpClient = null;
System.Console.WriteLine(strStatusMsg);
} // End Main Try
} // End static void Main
} // End class Program
} // End namespace tester
Here is the output.

And a stack trace.
at Renci.SshNet.Sftp.SftpSession.RequestOpen(String path, Flags flags, Boolean nullOnError) at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize, Boolean useAsync) at Renci.SshNet.Sftp.SftpFileStream..ctor(ISftpSession session, String path, FileMode mode, FileAccess access, Int32 bufferSize) at Renci.SshNet.SftpClient.OpenRead(String path) at tester.Program.Main(String[] args) in C:\Users\Will\Documents\Visual Studio 2015\Projects\tester\tester\Program.cs:line 38
Thanks! I'll fix it asap.
Just an FYI, I got the chance to try this against a different SFTP server (also not mine) and the error doesn't occur. It has something to do with the server. That's the same one from issue #100
The error happens with a SSH-2.0-WS_FTP-SSH_7.6.3 server (Ipswitch's WS FTP Server).
It doesn't happen with a SSH-2.0-srtSSHServer_11.00 server (SRT's Titan FTP Server).
I encountered this again while trying to test the dev branch for issue #100. Again, it's on that Ipswitch server. I'm beginning to hate that sever.
When I have more time, I'll look at it again. Let me know if you have questions.
@lochnar187 Would it somehow be possible for me to run a test against that server?
Does you have the same problem if you specify an absolute path in DownloadFile? For example:
using (var client = new SftpClient(new ConnectionInfo("host", "user", new PasswordAuthenticationMethod("user", "pwd"))))
{
client.Connect();
using (var ms = new MemoryStream())
{
client.DownloadFile("/some/absolute/path", ms);
}
}
@drieseng It's not my server and I doubt they would give you access but I will ask about a testing login.
I do use an absolute path, kind of. The home directory for my login is "prinftpuser", I can't go above that but as near as I can deduce, under the hood, that is an alias that maps to "\ustr\ftp\customerfiles\ftpfiles\prin". I only know that from the error message. So, I give the absolute path of "/prinftpuser/dbreplication/Logs/file.name" and the server fills in the alias and goes to "\ustr\ftp\customerfiles\ftpfiles\prin\dbreplication\Logs\file.name" and I get a file/folder not found error.
Have you tried if you can reproduce this issue with putty ? Might be an issue in WS_FTP.
If you just connect and list the files/directories, do you get the files/directory that are in
\ustr\ftp\customerfiles\ftpfiles\prin? Meaning, are you sure the home directory for your login maps to that directory?
@drieseng I haven't tried it with putty, but I will. Let me do some testing and get back to you.
@drieseng Just ran a quick test of file listing using an empty string for remote path, to test home directory of the login. I am using 2016.0.0 for this test. Calling ListDirectory, the test showed four items returned.

This list matches what is expected if the home directory is prinftpuser those being:
. .. emarbackup dbreplication
I also tried putty, Bitvise SSH Client 7.24, and was able to connect and SFTP the test file from /prinftpuser/dbreplication/Logs without issue. However, the log shows a problem getting the file size and it may well have something to do with this issue. Look at the last line, log follows:
14:52:33.238 Current date: 2017-01-29
14:52:33.238 SFTP session on 'xxxxx.xxxxx.com:22' started successfully. Using SFTP protocol version 4.
14:52:33.241 Listing local folder 'C:\data' succeeded.
14:52:33.241 Changing current local folder to 'C:\data' succeeded.
14:52:33.758 Listing remote folder '/prinftpuser' succeeded.
14:52:33.758 Changing current remote folder to '/prinftpuser' succeeded.
14:57:50.376 Listing remote folder '/prinftpuser/dbreplication' succeeded.
14:57:50.376 Changing current remote folder to '/prinftpuser/dbreplication' succeeded.
14:57:52.581 Listing remote folder '/prinftpuser/dbreplication/Logs' succeeded.
14:57:52.581 Changing current remote folder to '/prinftpuser/dbreplication/Logs' succeeded.
14:57:56.120 Passing download list to download manager succeeded.
14:57:56.123 Downloading remote file '/prinftpuser/dbreplication/Logs/LOG_us_prin_multi_replica_2016091806.SQB' started. Using 'auto/std' transfer mode.
14:57:57.744 Downloading remote file '/prinftpuser/dbreplication/Logs/LOG_us_prin_multi_replica_2016091806.SQB' completed. Getting file size for remote file '/prinftpuser/dbreplication/Logs/LOG_us_prin_multi_replica_2016091806.SQB' failed. FStat failed with SFTP error Failure: Folder not found: \\ustr\ftp\customerfiles\ftpfiles\prin\dbreplication\Logs\LOG_us_prin_multi_replica_2016091806.SQB. Getting file time for remote file '/prinftpuser/dbreplication/Logs/LOG_us_prin_multi_replica_2016091806.SQB' failed. FStat failed with SFTP error Failure: Folder not found: \\ustr\ftp\customerfiles\ftpfiles\prin\dbreplication\Logs\LOG_us_prin_multi_replica_2016091806.SQB.
It would seem that this is treated as a non-fatal error for Putty as it continues and gets the file anyway.
I'd like to be able to reproduce this issue so I can test a fix. Are you able to reproduce the issue using the latest WS_FTP server 2017 trail version, or have you been able to obtain a test login?
I'll give the trial version a go, hopefully in the next day or two, and I have put in a request for a test login so I'll let you know when I hear back from them.
Hi drieseng, Any update on this issue?
We are facing similar kind of issue.
Any help would be highly appreciated.
@drieseng Just that request response back, sending you a PM with details.
@drieseng Did you get my message?
Yes, I got your message. Just didn't have any time yet :(
Ran into the "Folder not found:" errors when trying to upload to a customers WS_FTP server ( 'WS_FTP-SSH_7.7' ).
I installed a Trial copy of WS_FTP Server 2017 ( 'WS_FTP-SSH_8.0.1' ) to see if I could reproduce the issue and the error went away. I suppose it could still be a setting on the customer WS_FTP server and not just version change. But I can confirm in my case the latest WS_FTP server works.