I have the following method where I send files to an sFTP server:
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;
}
And then I've made another method, where I check if the files have actually been uploaded and if it hasn't, then it uploads them. However, I want to add to the method, so that it deletes the folder and files locally on the machine, if it has been uploaded:
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);
}
}
The problem is, because I have a try/catch in my public static int Send(string fileName)
method, I can't get it to exit the if statement, if the Send(filePath); fails.
How can I exit the if statement, if the Send() method fails? Note: I did try and use a try/catch - that didn't work
CodePudding user response:
Could you not just use break;
to breakout of the IF if the result fails?
Change Send()
to return a bool
and in the exceptions return false
. Then do something like
if(!Send(filePath))
break;
etc
Should break out of the IF