I want to check if a remote folder exists before listing the files inside it. But this code is giving me SftpPathNotFoundException : No such file
I know that the folder that is being checked doesn't exist and thats the reason I would like to handle it.
var sftp = new SftpClient(sftpHost, username, password);
string sftpPath30s = "/home/Vendors/clips/1/4/4";
if (sftp.Exists(sftpPath30s))
{
var files30s = sftp.ListDirectory(sftpPath30s); //error here
if(files30s!=null)
{
Console.writeline("code doesn't reach here");
}
}
This code works fine for other existing folders like "/home/Vendors/clips/1/4/3" etc.
Let's say such a method exist. What then?
if (sftp.FolderExists(sftpPath30s))
{
var files30s = sftp.ListDirectory(sftpPath30s);
if(files30s!=null)
{
...
}
}
Is that Ok?
What happens if between checking if the file exists, and actually getting the file, the file is deleted, or moved?
So you need to write this:
if (sftp.FolderExists(sftpPath30s))
{
try
{
var files30s = sftp.ListDirectory(sftpPath30s);
if(files30s!=null)
{
...
}
}
catch (SftpPathNotFoundException) {}
}
At which point you don't gain anything from the check. You still have to add a try catch. Instead, it just means you have to do an extra call over the network and make your code more complex. So just do this:
try
{
var files30s = sftp.ListDirectory(sftpPath30s);
if(files30s!=null)
{
...
}
}
catch (SftpPathNotFoundException) {}
the sftp.Exists() method gives you false positive in that case, if it find a part of the directory it echo true even that not all the path is exist. i would recommend to change you'r code to this:
if (IsDirectoryExist(sftpPath30s))
{
var files30s = sftp.ListDirectory(sftpPath30s);
}
else
{
//Do what you want
}
and then the method 'IsDirectoryExists':
private bool IsDirectoryExists(string path)
{
bool isDirectoryExist = false;
try
{
sftp.ChangeDirectory(path);
isDirectoryExist = true;
}
catch (SftpPathNotFoundException)
{
return false;
}
return isDirectoryExist;
}
dont forget change back the directory you working on in case it metters!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.