/// <inheritdoc />
public Task UploadFileToServerAsync(Stream stream, string basePath, string fileName, bool overwrite = false)
{
if (String.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentNullException(nameof(fileName));
}
if (String.IsNullOrWhiteSpace(basePath))
{
throw new ArgumentNullException(nameof(basePath));
}
if (stream == null)
{
throw new ArgumentNullException(fileName);
}
if (stream.Length == 0)
{
throw new ArgumentException(LNG.SftpClient_CanNotBeEmpty, nameof(stream));
}
return(_retryAsyncPolicy.ExecuteAsync(() =>
{
EnsureConnected();
var filePath = GetFileFullPath(basePath, fileName);
if (_sftpClient.Exists(filePath))
{
// Check file size.
var attributes = _sftpClient.GetAttributes(filePath);
if (attributes.Size == stream.Length)
{
// Size is equal. Assume that files are equal. No need to upload.
_logger.LogWarning(String.Format(LNG.SftpClient_SameFileAlreadyExists, fileName));
return Task.CompletedTask;
}
if (overwrite)
{
// can overwrite, so delete file
_logger.LogWarning(String.Format(
LNG.SftpClient_Overwriting,
fileName,
attributes.Size,
stream.Length));
_sftpClient.DeleteFile(filePath);
}
else
{
// can't overwrite, it's error
throw new SshException(
String.Format(
LNG.SftpClient_DifferentFileAlreadyExists,
fileName,
attributes.Size,
stream.Length));
}
}
var sftpDirectory = Path.GetDirectoryName(filePath)
?.Replace(@"\", "/") // windows-linux compatibility
?? throw new InvalidOperationException("File path can't be mull");
if (!_sftpClient.Exists(sftpDirectory))
{
CreateDirectoryRecursively(sftpDirectory);
}
//TODO #3 check it, I think we don't need it here
// we need to set position to start because temp stream can be used in another places
stream.Position = 0;
return Task.Factory.FromAsync(
_sftpClient.BeginUploadFile(
stream,
filePath,
false,
null,
null),
_sftpClient.EndUploadFile);
}));
}