private void UploadSingleFile(ISftpFileUploader fileUploaderImplementation, string fileToUpload, string destinationPath, bool overWriteExistingFiles)
{
System.Diagnostics.Debug.WriteLine($"Will upload {fileToUpload}");
// check if file can be read
var fileAvailability = _fileAvailabilityChecker.CheckFileAvailability(fileToUpload);
if (fileAvailability.FileAvailabilityResult != FileAvailabilityResult.IsReadable)
{
_logger.LogError($"File '{fileAvailability.FileName}' could not be read - {fileAvailability.Description}/{fileAvailability.FileAvailabilityResult}");
return;
}
// Remove any trailing forward-slashes.
if (destinationPath.EndsWith("/"))
{
destinationPath = destinationPath.Substring(0, destinationPath.Length - 1);
}
string sftpServerDestinationFilePath = destinationPath + @"/" + Path.GetFileName(fileToUpload);
if (_sftpClient.Exists(sftpServerDestinationFilePath) && overWriteExistingFiles == false)
{
string fileNotUploadedMessage = ($"'{fileToUpload}' not uploaded - already exists in destination-dir '{destinationPath}'");
_logger.LogInformation(fileNotUploadedMessage);
}
else if (_sftpClient.Exists(sftpServerDestinationFilePath) && overWriteExistingFiles == true)
{
// Exists, overwrite if size changed or newer.
long existingFileSize = _sftpClient.GetAttributes(sftpServerDestinationFilePath).Size;
long localFileSize = new FileInfo(fileToUpload).Length;
bool isDifferentSize = existingFileSize != localFileSize;
DateTime existingFileTimeStamp = _sftpClient.GetLastWriteTimeUtc(sftpServerDestinationFilePath);
DateTime localFileTimeStamp = File.GetLastWriteTimeUtc(fileToUpload);
bool localFileIsNewer = localFileTimeStamp > existingFileTimeStamp;
if (isDifferentSize || localFileIsNewer)
{
fileUploaderImplementation.PerformFileUpload(fileToUpload, sftpServerDestinationFilePath, _sftpClient, _logger);
string fileUploadMessage = ($"Uploaded '{fileToUpload}' into destination-dir '{destinationPath}'");
_logger.LogInformation(fileUploadMessage);
}
else
{
string fileNotUploadedMessage = ($"'{fileToUpload}' not uploaded - already exists in destination-dir '{destinationPath}'");
_logger.LogInformation(fileNotUploadedMessage);
}
}
else
{
// All-new file, just upload it.
fileUploaderImplementation.PerformFileUpload(fileToUpload, sftpServerDestinationFilePath, _sftpClient, _logger);
string fileUploadMessage = ($"Uploaded '{fileToUpload}' into destination-dir '{destinationPath}'");
_logger.LogInformation(fileUploadMessage);
}
}