I am using Renci.SshNet library to get a list of files and directories recursively by using SFTP. I can able to connect SFTP site but I am not sure how to get a list of director
@Carlos Bos
This library has some quirks that make this recursive listing tricky because the interaction between the ChangeDirectory and ListDirectory do not work as you may expect.
correct
It works well when the ChangeDirectory() parameter is "."
but if you do
SftpClient sftp ...;
sftp.ChangeDirectory("some_folder");
//get file list
List fileList = sftp.ListDirectory("some_folder").ToList();
then there is an assertion because the ListDirectory() call expects "some_folder/some_folder"
The workaround I use is to save and restore the current directory before a remote upload/rename to "some_folder", and you need to list that folder before the operation (e.g to see the file already exists)
string working_directory = sftp.WorkingDirectory;
sftp.ChangeDirectory("some_folder");
sftp.RenameFile("name", "new_name");
sftp.ChangeDirectory(working_directory);
to check if the file exists, this call is sufficient
sftp.Exists(path)
or if you want to add some other criteria, like case sensitive or not
public FileExistence checkFileExists(string folder, string fileName)
{
//get file list
List fileList = sftp.ListDirectory(folder).ToList();
if (fileList == null)
{
return FileExistence.UNCONFIRMED;
}
foreach (SftpFile f in fileList)
{
Console.WriteLine(f.ToString());
//a not case sensitive comparison is made
if (f.IsRegularFile && f.Name.ToLower() == fileName.ToLower())
{
return FileExistence.EXISTS;
}
}
//if not found in traversal , it does not exist
return FileExistence.DOES_NOT_EXIST;
}
where FileExistence is
public enum FileExistence
{
EXISTS,
DOES_NOT_EXIST,
UNCONFIRMED
};