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

Exit if statement when try catch in different function has hit

我使用以下方法将文件发送到 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() 更改为 return a bool 并且在例外情况下 return false。然后做一些像

if(!Send(filePath))
    break;
etc

应该突破IF