private void SyncDirectory(IFtpClient client, string remotePath, string localPath, bool isDel) { var localFolder = new DirectoryInfo(localPath); var infos = localFolder.GetFileSystemInfos(); foreach (var info in infos) { if (!client.IsConnected) { client.Connect(); } if (info is FileInfo) { var size = (info as FileInfo).Length; var remoteFile = Path.Combine(remotePath, info.Name); if (!client.FileExists(remoteFile) || client.GetFileSize(remoteFile) != size) { client.UploadFile(info.FullName, remoteFile); Logger.Info($"Uploaded==>{info.FullName}"); } } else if (info is DirectoryInfo) { var remoteFile = Path.Combine(remotePath, info.Name); if (!client.DirectoryExists(remoteFile)) { client.CreateDirectory(remoteFile); Logger.Info($"CreateFtpDirectory==>{remoteFile}"); } SyncDirectory(client, Path.Combine(remotePath, info.Name), info.FullName, isDel); } } if (isDel) { var items = client.GetListing(remotePath); foreach (var item in items) { if (infos.All(info => info.Name != item.Name)) { if (item.Type == FtpFileSystemObjectType.File) { client.DeleteFile(item.FullName); } else if (item.Type == FtpFileSystemObjectType.Directory) { client.DeleteDirectory(item.FullName); } Logger.Info($"DeletedFtp==>{item.FullName}"); } } } }
private void BackupDirectory(IFtpClient client, string remotePath, string localPath, bool isDel) { var items = client.GetListing(remotePath); foreach (var item in items) { if (!client.IsConnected) { client.Connect(); } if (item.Type == FtpFileSystemObjectType.File) { var size = client.GetFileSize(item.FullName); var localFile = Path.Combine(localPath, item.Name); if (!File.Exists(localFile) || new FileInfo(localFile).Length != size) { client.DownloadFile(localFile, item.FullName); Logger.Info($"Downloaded==>{item.FullName}"); } } else if (item.Type == FtpFileSystemObjectType.Directory) { if (!Directory.Exists(item.FullName)) { Directory.CreateDirectory(item.FullName); Logger.Info($"CreateDirectory==>{item.FullName}"); } BackupDirectory(client, item.FullName, Path.Combine(localPath, item.Name), isDel); } } if (isDel) { var localFolder = new DirectoryInfo(localPath); var infos = localFolder.GetFileSystemInfos(); foreach (var info in infos) { if (items.All(item => item.Name != info.Name)) { if (info is DirectoryInfo) { (info as DirectoryInfo).Delete(true); } else { info.Delete(); } Logger.Info($"Deleted==>{info.FullName}"); } } } }