我有以下方法將檔案發送到 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 - 那沒有用
uj5u.com熱心網友回復:
如果結果失敗,你不能只用break;突破 IF 嗎?
更改Send()為 return abool并在例外中 return false。然后做類似的事情
if(!Send(filePath))
break;
etc
應該突破IF
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/457702.html
