当不同函数中的try-catch命中时退出if语句



我有以下方法将文件发送到sFTP服务器:

public static int Send(string fileName)
{
var connectionInfo = new ConnectionInfo(_host, _userName, new PasswordAuthenticationMethod(_userName, _password));
// upload file
using (var client = new SftpClient(connectionInfo))
{
try
{
client.Connect();
}
catch (Exception e)
{
Console.WriteLine(e.Message + ". No internet connection");
}

try
{
client.ChangeDirectory($"/{Environment.MachineName}/{_date.ToString("d")}");
}
catch(Renci.SshNet.Common.SshConnectionException e)
{
Console.WriteLine(e.Message + ". No internet connection");
}
catch(Exception)
{
client.CreateDirectory($"/{Environment.MachineName}/{_date.ToString("d")}");
client.ChangeDirectory($"/{Environment.MachineName}/{_date.ToString("d")}");
}
using (var uploadFileStream = System.IO.File.OpenRead(fileName))
{
try
{
client.UploadFile(uploadFileStream, fileName, true);
}
catch (Exception)
{
Console.WriteLine("No internet connection");
}

}
client.Disconnect();
}
return 0;
}

然后我做了另一种方法,我检查文件是否真的上传了,如果没有,它就会上传。然而,我想添加到该方法中,以便它删除机器上本地的文件夹和文件,如果它已经上传:

foreach (string filePath in sendLocalFiles)
{
var path = Path.GetFileNameWithoutExtension(filePath);
if (!client.Exists(filePath))
{
Send(filePath);
File.Delete(filePath);
Directory.Delete($@"C:Temp{Environment.MachineName}{_date.ToString("d")}{path}", true);
}
}

问题是,因为我的public static int Send(string fileName)方法中有一个try/catch,所以我无法让它退出if语句,如果Send(filePath(;失败。

如果Send((方法失败,我如何退出if语句?注意:我确实尝试过使用try/catch,但不起作用

如果结果失败,您不能只使用break;来突破IF吗?

更改Send()以返回bool,在异常情况下返回false。然后做一些类似的事情

if(!Send(filePath))
break;
etc

应突破中频

最新更新