using System;
using CSharpFunctionalExtensions;
using WinSCP;
namespace AAC.SettlementEngine.UI.DataAccess.Utilities
{
public class FtpProcessor
{
private readonly string _hostName;
private readonly string _password;
private readonly Protocol _protocol;
private readonly string _userName;
///
/// Setup Sessions credential
///
///
///
///
/// Default is SFTP (support FTP)
public FtpProcessor(string hostName, string userName, string password, Protocol protocol = Protocol.Sftp)
{
// the client will read the credential
// information from a configuration file
_protocol = protocol;
_hostName = hostName;
_userName = userName;
_password = password;
}
///
/// Download one file from a remote directory to a local directory.
/// The method downloads files only. It throws when the source path points to a directory.
/// If the target local directory does not exist, it is created.
///
///
/// Full path to the remote file to download.
///
///
/// Full path to the local directory to download the file to.
/// The directory is created, if it does not exist.
///
///
/// Result.Fail if downloading of a file has failed
/// Result.Success if downloading of a file is successful
///
public Result RetrieveFile(string remotePath, string downloadPath)
{
var sessionOptions = new SessionOptions
{
Protocol = _protocol,
HostName = _hostName,
UserName = _userName,
Password = _password
};
try
{
using (var session = new Session())
{
// Connect
session.Open(sessionOptions);
var transferOptions = new TransferOptions
{
TransferMode = TransferMode.Binary
};
var fileExist = session.FileExists(remotePath);
if (fileExist)
{
// Download files
var transferResult = session.GetFiles(remotePath, downloadPath, false, transferOptions);
// Throw on any error
transferResult.Check();
}
else
{
return Result.Failure($"Error: File {remotePath} does not exists.");
}
}
}
catch (Exception e)
{
return Result.Failure($"{e.Message}");
}
return Result.Success();
}
}
}