Path: redb-route/redb.Route.Ftp/FtpFileOperations.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Ftp/FtpFileOperations.cs ---- using System.Text; using FluentFTP; using redb.Route.GenericFile; namespace redb.Route.Ftp; /// /// Implements for FTP via FluentFTP. /// Manages lifecycle through Connect/Disconnect. /// All path operations use forward-slash convention. /// internal sealed class FtpFileOperations : IRemoteFileOperations { private readonly FtpEndpointOptions _options; private AsyncFtpClient? _client; /// Creates FTP file operations for the given endpoint options. public FtpFileOperations(FtpEndpointOptions options) { ArgumentNullException.ThrowIfNull(options); _options = options; } /// The underlying FluentFTP client (null until connected). internal AsyncFtpClient? Client => _client; // ═══════════════════════════════════════════════════════════════════ // CONNECTION LIFECYCLE // ═══════════════════════════════════════════════════════════════════ /// public bool IsConnected => _client is { IsConnected: true }; /// public async Task ConnectAsync(CancellationToken ct = default) { if (_client != null) { if (_client.IsConnected) await _client.Disconnect(ct).ConfigureAwait(false); _client.Dispose(); _client = null; } _client = new AsyncFtpClient(_options.Host, _options.Username, _options.Password, _options.Port); _client.Config.DataConnectionType = _options.PassiveMode ? FtpDataConnectionType.AutoPassive : FtpDataConnectionType.AutoActive; _client.Config.ConnectTimeout = _options.ConnectionTimeout; _client.Config.DataConnectionConnectTimeout = _options.ConnectionTimeout; _client.Config.ReadTimeout = _options.OperationTimeout; _client.Config.TransferChunkSize = 65536; // transferType: Ascii asks the server for line-ending conversion, Binary moves raw bytes. // Declared and documented from day one, wired to nothing until the options sweep. var dataType = _options.TransferType == FtpTransferType.Ascii ? FtpDataType.ASCII : FtpDataType.Binary; _client.Config.UploadDataType = dataType; _client.Config.DownloadDataType = dataType; if (_options.UseFtps) { _client.Config.EncryptionMode = FtpEncryptionMode.Explicit; if (!_options.ValidateCertificate) _client.ValidateCertificate += (_, e) => e.Accept = true; } await _client.Connect(ct).ConfigureAwait(false); } /// public async Task DisconnectAsync(CancellationToken ct = default) { if (_client != null) { try { if (_client.IsConnected) await _client.Disconnect(ct).ConfigureAwait(false); } finally { _client.Dispose(); _client = null; } } } // ═══════════════════════════════════════════════════════════════════ // ENUMERATION // ═══════════════════════════════════════════════════════════════════ /// public async Task> ListFilesAsync( string directory, bool recursive, int maxDepth, int minDepth, Func? directoryFilter = null, CancellationToken ct = default) { var client = RequireClient(); var result = new List(); await EnumerateFilesAsync(client, directory, directory, 0, recursive, maxDepth, minDepth, directoryFilter, result, ct) .ConfigureAwait(false); return result; } private async Task EnumerateFilesAsync( AsyncFtpClient client, string dirPath, string basePath, int depth, bool recursive, int maxDepth, int minDepth, Func? directoryFilter, List result, CancellationToken ct) { FtpListItem[] items; try { items = await client.GetListing(dirPath, FtpListOption.Modify, ct).ConfigureAwait(false); } catch (Exception) when (_options.IgnoreFileNotFoundOrPermissionError) { return; } foreach (var item in items) { if (item.Type == FtpObjectType.Directory) { if (recursive && (maxDepth == 0 || depth < maxDepth)) { var subPath = CombinePath(dirPath, item.Name); // Asked before the descent: a directory turned down here costs no listing. if (directoryFilter != null && !directoryFilter(subPath, GetRelativePath(basePath, subPath))) continue; await EnumerateFilesAsync(client, subPath, basePath, depth + 1, recursive, maxDepth, minDepth, directoryFilter, result, ct) .ConfigureAwait(false); } } else if (item.Type == FtpObjectType.File) { if (minDepth > 0 && depth < minDepth) continue; result.Add(new GenericFileInfo { Name = item.Name, FullPath = item.FullName, BasePath = basePath, Length = item.Size, LastModified = new DateTimeOffset(item.Modified.ToUniversalTime(), TimeSpan.Zero), Depth = depth }); } } } // ═══════════════════════════════════════════════════════════════════ // READ // ═══════════════════════════════════════════════════════════════════ /// public async Task ReadAllBytesAsync(string path, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(); await client.DownloadStream(ms, path, token: ct).ConfigureAwait(false); return ms.ToArray(); } /// public async Task OpenReadAsync(string path, CancellationToken ct = default) { var client = RequireClient(); var ms = new MemoryStream(); await client.DownloadStream(ms, path, token: ct).ConfigureAwait(false); ms.Position = 0; return ms; } // ═══════════════════════════════════════════════════════════════════ // WRITE // ═══════════════════════════════════════════════════════════════════ /// public async Task WriteAsync(string path, byte[] data, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(data); var status = await client.UploadStream(ms, path, FtpRemoteExists.Overwrite, true, null, ct) .ConfigureAwait(false); if (status == FtpStatus.Failed) throw new IOException($"FTP upload failed: {path}"); } /// public async Task WriteAsync(string path, Stream data, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(); await data.CopyToAsync(ms, ct).ConfigureAwait(false); ms.Position = 0; var status = await client.UploadStream(ms, path, FtpRemoteExists.Overwrite, true, null, ct) .ConfigureAwait(false); if (status == FtpStatus.Failed) throw new IOException($"FTP upload failed: {path}"); } /// public async Task AppendAsync(string path, byte[] data, CancellationToken ct = default) { var client = RequireClient(); using var ms = new MemoryStream(data); var status = await client.UploadStream(ms, path, FtpRemoteExists.AddToEnd, true, null, ct) .ConfigureAwait(false); if (status == FtpStatus.Failed) throw new IOException($"FTP append failed: {path}"); } /// public async Task AppendTextAsync(string path, string text, Encoding encoding, CancellationToken ct = default) { var data = encoding.GetBytes(text); await AppendAsync(path, data, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // FILE OPERATIONS // ═══════════════════════════════════════════════════════════════════ /// public async Task ExistsAsync(string path, CancellationToken ct = default) { var client = RequireClient(); return await client.FileExists(path, ct).ConfigureAwait(false); } /// public async Task DeleteAsync(string path, CancellationToken ct = default) { var client = RequireClient(); await client.DeleteFile(path, ct).ConfigureAwait(false); } /// public async Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct = default) { var client = RequireClient(); if (overwrite && await client.FileExists(destination, ct).ConfigureAwait(false)) { await client.DeleteFile(destination, ct).ConfigureAwait(false); } await client.MoveFile(source, destination, FtpRemoteExists.Overwrite, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // DIRECTORY OPERATIONS // ═══════════════════════════════════════════════════════════════════ /// public async Task CreateDirectoryAsync(string path, CancellationToken ct = default) { var client = RequireClient(); await client.CreateDirectory(path, true, ct).ConfigureAwait(false); } /// public async Task DirectoryExistsAsync(string path, CancellationToken ct = default) { var client = RequireClient(); return await client.DirectoryExists(path, ct).ConfigureAwait(false); } // ═══════════════════════════════════════════════════════════════════ // PATH HELPERS // ═══════════════════════════════════════════════════════════════════ /// public string CombinePath(string basePath, string relativePath) { if (string.IsNullOrEmpty(basePath)) return "/" + relativePath; if (string.IsNullOrEmpty(relativePath)) return basePath; return basePath.TrimEnd('/') + "/" + relativePath.TrimStart('/'); } /// public string GetParentPath(string path) { var lastSlash = path.LastIndexOf('/'); return lastSlash <= 0 ? "/" : path[..lastSlash]; } /// public string GetFileName(string path) { var lastSlash = path.LastIndexOf('/'); return lastSlash >= 0 ? path[(lastSlash + 1)..] : path; } /// public string GetFileNameWithoutExtension(string name) { var fileName = GetFileName(name); var dotIndex = fileName.LastIndexOf('.'); return dotIndex > 0 ? fileName[..dotIndex] : fileName; } /// public string GetExtension(string name) { var fileName = GetFileName(name); var dotIndex = fileName.LastIndexOf('.'); return dotIndex >= 0 ? fileName[dotIndex..] : ""; } /// public string GetRelativePath(string basePath, string fullPath) { if (fullPath.StartsWith(basePath, StringComparison.Ordinal)) { var relative = fullPath[basePath.Length..].TrimStart('/'); return string.IsNullOrEmpty(relative) ? fullPath : relative; } return fullPath; } /// public bool IsAbsolutePath(string path) { return path.StartsWith('/'); } // ═══════════════════════════════════════════════════════════════════ // INTERNAL // ═══════════════════════════════════════════════════════════════════ private AsyncFtpClient RequireClient() { return _client ?? throw new InvalidOperationException("FTP client is not connected. Call ConnectAsync first."); } }