'Check if Remote folder exists - Renci.ssh
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.
Solution 1:[1]
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) {}
Solution 2:[2]
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!
Solution 3:[3]
What about this:
string [] seperator = new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }
foreach(string dir in destinationFolder.Split(seperator))
if (!client.Exists(dir))
client.CreateDirectory(dir);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Suraj Rao |
| Solution 2 | knightsb |
| Solution 3 | Viktor |
