2017-07-14 75 views
0

我试图从移动文件通过ftp到B是这样的:处理一般例外在特定情况下

ftpClient.Rename(sourcePathName, targetPathName); 

我想捕捉和处理时有文件要发生的所有异常移动未找到。但是Rename会抛出值为{"file/directory not found"}的通用异常FtpCommandException。不幸的是,这种例外情况在其他一些情况下引发。

我不觉得比较例外的值是像一个干净的方法:

if("file/directory not found".equals(exception.value)) ... 
+0

如果你需要异常被不同的处理你不能用它自己的try/catch块分割你的命名代码出了自己的作用? – uk2k05

回答

0

也许哟ü应检查文件是否试图重命名之前存在:

if (ftpClient.FileExists(sourcePathName)){ 
    ftpClient.Rename(sourcePathName, targetPathName); 
} 
+0

愚蠢的我......当然这是它。 – mosquito87

1

C#6日起,您可以使用异常过滤

try 
{ 
    // your code 
} 
catch(FtpCommandException ex) 
     when (ex.Value == "file/directory not found") 
{ 
    // do something with this exception 
} 

前C#6你唯一的选择是一个条件渔获:

try 
{ 
    // your code 
} 
catch(FtpCommandException ex) 
{ 
    if(ex.Value == "file/directory not found") 
    { 
     // do something with this exception 
    } 
}