C# 检查远程文件夹是否存在-Renci.ssh
在列出其中的文件之前,我想检查一下远程文件夹是否存在。 但是这段代码给了我C# 检查远程文件夹是否存在-Renci.ssh,c#,ssh,C#,Ssh,在列出其中的文件之前,我想检查一下远程文件夹是否存在。 但是这段代码给了我sftpathNotFoundException:没有这样的文件 我知道正在检查的文件夹不存在,这就是我想处理它的原因 var sftp = new SftpClient(sftpHost, username, password); string sftpPath30s = "/home/Vendors/clips/1/4/4"; if (sftp.Exists(sftpPath30s)) { var f
sftpathNotFoundException:没有这样的文件
我知道正在检查的文件夹不存在,这就是我想处理它的原因
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");
}
}
此代码适用于其他现有文件夹,如“/home/Vendors/clips/1/4/3”等。在这种情况下,sftp.Exists()方法会给出误报,如果它找到目录的一部分,即使不是所有路径都存在,它也会回显true。
我建议将您的代码更改为:
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;
}
别忘了把你正在处理的目录换回来,以防它出错
假设存在这样一种方法。然后呢
if(sftp.FolderExists(sftpPath30s))
{
var files30s=sftp.ListDirectory(sftpPath30s);
如果(files30s!=null)
{
...
}
}
可以吗
如果在检查文件是否存在和实际获取文件之间,文件被删除或移动,会发生什么情况
所以你需要写下:
if(sftp.FolderExists(sftpPath30s))
{
尝试
{
var files30s=sftp.ListDirectory(sftpPath30s);
如果(files30s!=null)
{
...
}
}
catch(sftpatthnotfoundexception){}
}
在这一点上,你不会从支票中得到任何东西。您仍然需要添加一个try-catch。相反,它只是意味着你必须通过网络进行额外的调用,使你的代码更加复杂。那么就这么做吧:
试试看
{
var files30s=sftp.ListDirectory(sftpPath30s);
如果(files30s!=null)
{
...
}
}
catch(sftpatthnotfoundexception){}