2015-04-06 147 views
0

我想检查一个远程文件夹是否存在,然后再列出其中的文件。 但此代码给我SftpPathNotFoundException : No such file检查远程文件夹是否存在 - Renci.ssh

我知道被检查的文件夹不存在,这就是我想要处理它的原因。

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"); 
     } 
    } 

此代码工作正常,像 “/家/供应商/短片/ 1/4/3” 等

回答

0

的sftp.Exists其他现有的文件夹()方法,给出了在这种情况下,你的假阳性,如果它发现目录的一部分它回显真,即使并不是所有的路径都存在。 我会建议找你的代码改成这样:

if (IsDirectoryExist(sftpPath30s)) 
    { 
    var files30s = sftp.ListDirectory(sftpPath30s); 

    } 
else 
{ 
    //Do what you want 
} 

,然后方法“IsDirectoryExists”:

 private bool IsDirectoryExists(string path) 
    { 
     bool isDirectoryExist = false; 

     try 
     { 
      sftp.ChangeDirectory(path); 
      isDirectoryExist = true; 
     } 
     catch (SftpPathNotFoundException) 
     { 
      return false; 
     } 
     return isDirectoryExist; 
    } 

不要忘记换回来你工作的目录在它麦特斯情况下!

相关问题