using FluentFTP; using System; using System.Collections.Generic; using System.Linq; using System.Net.Security; namespace EgwProxy.Ftp { /// /// Client per operazioni FTP, basato su FluentFTP: https://github.com/robinrodricks/FluentFTP/wiki/Quick-Start-Example /// public class Manager { #region Public Constructors /// /// Inizializzazione di oggetto per comunicazione FTP /// /// /// /// /// /// public Manager(string server, string userName, string passwd, string rawCert, bool skipCert) { _server = server; _userName = userName; _passwd = passwd; _skipCert = skipCert; _rawCert = rawCert; if (!string.IsNullOrEmpty(server)) { // se ho user/pwd è autenticato... if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passwd)) { client = new FtpClient(server, userName, passwd); } //.. altrimenti anonimo... else { client = new FtpClient(server); } } } #endregion Public Constructors #region Public Methods /// /// Creazione directory remota /// /// Nome directory remota da creare (ad es: @"/public_html/videos") public bool createDir(string remoteDir) { tryConnect(); // upload della folder + files, cancellazione extra files = mirroring bool answ = client.CreateDirectory(remoteDir); // chiudo! client.Disconnect(); return answ; } /// /// Eliminazionedirectory remota /// /// Nome directory remota da eliminare public bool deleteDir(string remoteDir) { tryConnect(); bool answ = false; try { // Elimina folder client.DeleteDirectory(remoteDir); answ = true; } catch { } // chiudo! client.Disconnect(); return answ; } /// /// Eliminazionedirectory remota /// /// Nome file remoto da eliminare public bool deleteFile(string remoteFile) { tryConnect(); bool answ = false; try { // Elimina folder client.DeleteFile(remoteFile); answ = true; } catch { } // chiudo! client.Disconnect(); return answ; } /// /// Verifica esistenza directory su server FTP remoto /// /// Percorso remoto da testare (ad es "/htdocs/extras/") /// public bool dirExists(string remotePath) { tryConnect(); bool answ = client.DirectoryExists(remotePath); // chiudo! client.Disconnect(); return answ; } /// /// Verifica esistenza file su server FTP remoto /// /// Percorso remoto da testare (ad es "/htdocs/big2.txt") /// public bool fileExists(string remotePath) { tryConnect(); bool answ = client.FileExists(remotePath); // chiudo! client.Disconnect(); return answ; } /// /// Scaricamento intera directory, modalità MIRROR /// /// Path directory da inviare (ad es:@"C:\website\videos\") /// Nome remoto file per caricamento (ad es: @"/public_html/videos") public bool getDir(string dirPath, string remoteDir) { bool answ = false; tryConnect(); try { // upload della folder + files, cancellazione extra files = mirroring var result = client.DownloadDirectory(dirPath, remoteDir, FtpFolderSyncMode.Mirror); answ = (result != null && result.Count > 0); } catch { } // chiudo! client.Disconnect(); return answ; } /// /// Download singolo file /// /// Path locale del file da inviare (ad es: @"C:\MyVideo.mp4") /// NOme remoto file per caricamento (ad es: "/htdocs/MyVideo.mp4") public bool getFile(string fileName, string remoteName) { bool answ = false; tryConnect(); // effettuo caricamento puntuale var result = client.DownloadFile(fileName, remoteName); answ = result == FtpStatus.Success; // chiudo! client.Disconnect(); return answ; } /// /// Mostra contenuto directory remota /// /// Nome directory remota da leggere (ad es: @"/public_html/videos") /// Indica se fare search ricorsivo public List listDir(string remoteDir, bool recurse) { tryConnect(); // upload della folder + files, cancellazione extra files = mirroring FtpListItem[] dirContent; if (recurse) { dirContent = client.GetListing(remoteDir, FtpListOption.Recursive); } else { dirContent = client.GetListing(remoteDir); } client.Disconnect(); var answ = dirContent.Select(x => $"{x.Type} - {x.Name}").ToList(); // chiudo! return answ; } /// /// Caricamento intera directory, modalità MIRROR /// /// Path directory da inviare (ad es:@"C:\website\videos\") /// Nome remoto file per caricamento (ad es: @"/public_html/videos") public bool sendDir(string dirPath, string remoteDir) { bool answ = false; tryConnect(); // upload della folder + files, cancellazione extra files = mirroring var result = client.UploadDirectory(dirPath, remoteDir, FtpFolderSyncMode.Mirror); answ = (result != null && result.Count > 0); // chiudo! client.Disconnect(); return answ; } /// /// Caricamento singolo file /// /// Path locale del file da inviare (ad es: @"C:\MyVideo.mp4") /// NOme remoto file per caricamento (ad es: "/htdocs/MyVideo.mp4") public bool sendFile(string fileName, string remoteName) { bool answ = false; tryConnect(); // effettuo caricamento puntuale var result = client.UploadFile(fileName, remoteName); answ = result == FtpStatus.Success; // se insuccesso --> controllo se ci sia file... if (!answ) { answ = fileExists(remoteName); } // chiudo! client.Disconnect(); return answ; } /// /// Verifica connessione con server FTP remoto /// /// public bool serverOk() { tryConnect(); bool answ = client.IsConnected; // chiudo! client.Disconnect(); return answ; } /// /// Restituisce tipo server remoto /// /// public string serverType() { tryConnect(); FtpServer srvType = client.ServerType; // chiudo! client.Disconnect(); return $"{srvType}"; } #endregion Public Methods #region Protected Fields protected bool _skipCert = false; #endregion Protected Fields #region Protected Properties protected string _passwd { get; set; } = ""; protected string _rawCert { get; set; } = ""; protected string _server { get; set; } = ""; protected string _userName { get; set; } = ""; #endregion Protected Properties #region Private Properties private FtpClient client { get; set; } #endregion Private Properties #region Private Methods private void Client_ValidateCertificate(FluentFTP.Client.BaseClient.BaseFtpClient control, FtpSslValidationEventArgs e) { if (e.PolicyErrors == SslPolicyErrors.None || _skipCert || e.Certificate.GetRawCertDataString() == _rawCert) { e.Accept = true; } else { Console.WriteLine($"{e.PolicyErrors}"); Console.WriteLine($"Cert:{Environment.NewLine}{e.Certificate}"); Console.WriteLine($"RawString:{Environment.NewLine}{e.Certificate.GetRawCertDataString()}"); throw new Exception($"{e.PolicyErrors}{Environment.NewLine}{e.Certificate.GetRawCertDataString()}"); } } private void tryConnect() { // connect to the server and automatically detect working FTP settings if (!client.IsConnected) { var profiles = client.AutoDetect(); #if false // if any profiles are found, print the code to the console if (profiles.Count > 0) { var code = profiles[0].ToCode(); Console.WriteLine(code); } #endif client.ValidateCertificate += Client_ValidateCertificate; client.AutoConnect(); } } #endregion Private Methods } }