Path: redb-route/redb.Route.Sftp/SftpFileOperations.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.Sftp/SftpFileOperations.cs
----
using System.Text;
using Renci.SshNet;
using Renci.SshNet.Sftp;
using redb.Route.GenericFile;
namespace redb.Route.Sftp;
///
/// Implements for SFTP via SSH.NET.
/// Manages lifecycle through Connect/Disconnect.
/// All path operations use forward-slash UNIX convention.
///
internal sealed class SftpFileOperations : IRemoteFileOperations
{
private readonly SftpEndpointOptions _options;
private SftpClient? _client;
/// Creates SFTP file operations for the given endpoint options.
public SftpFileOperations(SftpEndpointOptions options)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
}
/// The underlying SSH.NET SFTP client (null until connected).
internal SftpClient? Client => _client;
// ═══════════════════════════════════════════════════════════════════
// CONNECTION LIFECYCLE
// ═══════════════════════════════════════════════════════════════════
///
public bool IsConnected => _client is { IsConnected: true };
///
public Task ConnectAsync(CancellationToken ct = default)
{
if (_client != null)
{
if (_client.IsConnected) _client.Disconnect();
_client.Dispose();
_client = null;
}
_client = SftpClientFactory.Create(_options);
_client.Connect();
return Task.CompletedTask;
}
///
public Task DisconnectAsync(CancellationToken ct = default)
{
if (_client != null)
{
try
{
if (_client.IsConnected)
_client.Disconnect();
}
finally
{
_client.Dispose();
_client = null;
}
}
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// ENUMERATION
// ═══════════════════════════════════════════════════════════════════
///
public Task> ListFilesAsync(
string directory, bool recursive, int maxDepth, int minDepth,
Func? directoryFilter = null,
CancellationToken ct = default)
{
var client = RequireClient();
var result = EnumerateFiles(client, directory, directory, 0, recursive, maxDepth, minDepth, directoryFilter);
return Task.FromResult(result);
}
private List EnumerateFiles(
SftpClient client, string dirPath, string basePath,
int depth, bool recursive, int maxDepth, int minDepth,
Func? directoryFilter)
{
var result = new List();
IEnumerable entries;
try
{
entries = client.ListDirectory(dirPath);
}
catch (Exception) when (_options.IgnoreFileNotFoundOrPermissionError)
{
return result;
}
foreach (var entry in entries)
{
if (entry.Name is "." or "..")
continue;
if (entry.IsDirectory)
{
if (recursive && (maxDepth == 0 || depth < maxDepth))
{
var subPath = CombinePath(dirPath, entry.Name);
// Asked before the descent: a directory turned down here costs no listing,
// which is the point of filterDirectory on a tree of partner directories.
if (directoryFilter != null && !directoryFilter(subPath, GetRelativePath(basePath, subPath)))
continue;
try
{
result.AddRange(EnumerateFiles(client, subPath, basePath, depth + 1, recursive, maxDepth, minDepth, directoryFilter));
}
catch (Renci.SshNet.Common.SftpPathNotFoundException)
when (!_options.DirectoryMustExist && !client.Exists(subPath))
{
// The subdirectory vanished between the parent listing and the descent
// (another process consumed it). directoryMustExist=false (default): skip;
// true: let it escape - the poll reports the inconsistency.
// The Exists probe keeps this a TOCTOU guard and nothing more: a directory
// that still exists means the path was built wrong - that must escape,
// not become a silent per-poll skip.
}
}
}
else if (entry.IsRegularFile)
{
if (minDepth > 0 && depth < minDepth)
continue;
result.Add(new GenericFileInfo
{
Name = entry.Name,
FullPath = entry.FullName,
BasePath = basePath,
Length = entry.Length,
LastModified = new DateTimeOffset(entry.LastWriteTime.ToUniversalTime(), TimeSpan.Zero),
Depth = depth,
Extras = new Dictionary
{
["UserId"] = entry.UserId,
["GroupId"] = entry.GroupId
}
});
}
}
return result;
}
// ═══════════════════════════════════════════════════════════════════
// READ
// ═══════════════════════════════════════════════════════════════════
///
public Task ReadAllBytesAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
using var ms = new MemoryStream();
client.DownloadFile(path, ms);
return Task.FromResult(ms.ToArray());
}
///
public Task OpenReadAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
Stream stream = client.OpenRead(path);
return Task.FromResult(stream);
}
// ═══════════════════════════════════════════════════════════════════
// WRITE
// ═══════════════════════════════════════════════════════════════════
///
public Task WriteAsync(string path, byte[] data, CancellationToken ct = default)
{
var client = RequireClient();
using var ms = new MemoryStream(data);
client.UploadFile(ms, path);
return Task.CompletedTask;
}
///
public async Task WriteAsync(string path, Stream data, CancellationToken ct = default)
{
var client = RequireClient();
// Copy to MemoryStream first to ensure seekability
using var ms = new MemoryStream();
await data.CopyToAsync(ms, ct).ConfigureAwait(false);
ms.Position = 0;
client.UploadFile(ms, path);
}
///
public Task AppendAsync(string path, byte[] data, CancellationToken ct = default)
{
var client = RequireClient();
var encoding = ResolveEncoding();
using var writer = client.AppendText(path, encoding);
writer.Write(encoding.GetString(data));
writer.Flush();
return Task.CompletedTask;
}
///
public Task AppendTextAsync(string path, string text, Encoding encoding, CancellationToken ct = default)
{
var client = RequireClient();
using var writer = client.AppendText(path, encoding);
writer.Write(text);
writer.Flush();
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// FILE OPERATIONS
// ═══════════════════════════════════════════════════════════════════
///
public Task ExistsAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
return Task.FromResult(client.Exists(path));
}
///
public Task DeleteAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
client.DeleteFile(path);
return Task.CompletedTask;
}
///
public Task MoveAsync(string source, string destination, bool overwrite, CancellationToken ct = default)
{
var client = RequireClient();
if (overwrite && client.Exists(destination))
{
client.DeleteFile(destination);
}
client.RenameFile(source, destination);
return Task.CompletedTask;
}
// ═══════════════════════════════════════════════════════════════════
// DIRECTORY OPERATIONS
// ═══════════════════════════════════════════════════════════════════
///
public Task CreateDirectoryAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
EnsureRemoteDirectoryExists(client, path);
return Task.CompletedTask;
}
///
public Task DirectoryExistsAsync(string path, CancellationToken ct = default)
{
var client = RequireClient();
return Task.FromResult(client.Exists(path));
}
///
/// Recursively creates all directories in the given path.
///
internal static void EnsureRemoteDirectoryExists(SftpClient client, string path)
{
if (client.Exists(path))
return;
var parts = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
var current = "";
foreach (var part in parts)
{
current += "/" + part;
if (!client.Exists(current))
{
client.CreateDirectory(current);
}
}
}
// ═══════════════════════════════════════════════════════════════════
// PATH HELPERS
// ═══════════════════════════════════════════════════════════════════
// The SFTP protocol's one true separator. The separator option only controls whether the
// INPUTS are normalized (Auto) or taken byte-for-byte (Unix) - see SftpSeparator.
private const char Sep = '/';
///
public string CombinePath(string basePath, string relativePath)
{
if (_options.Separator == SftpSeparator.Auto)
{
basePath = basePath?.Replace('\\', '/') ?? "";
relativePath = relativePath?.Replace('\\', '/') ?? "";
}
if (string.IsNullOrEmpty(basePath)) return Sep + relativePath;
if (string.IsNullOrEmpty(relativePath)) return basePath;
return basePath.TrimEnd(Sep) + Sep + relativePath.TrimStart(Sep);
}
///
public string GetParentPath(string path)
{
var lastSlash = path.LastIndexOf(Sep);
return lastSlash <= 0 ? Sep.ToString() : path[..lastSlash];
}
///
public string GetFileName(string path)
{
var lastSlash = path.LastIndexOf(Sep);
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('/');
}
// ═══════════════════════════════════════════════════════════════════
// SFTP-SPECIFIC HELPERS
// ═══════════════════════════════════════════════════════════════════
///
/// Applies POSIX chmod to a file or directory.
///
internal void ApplyChmod(string path, string octalPermissions)
{
var client = RequireClient();
var mode = SftpEndpointOptions.ParseOctalPermissions(octalPermissions);
var attrs = client.GetAttributes(path);
attrs.SetPermissions(mode);
client.SetAttributes(path, attrs);
}
///
/// Gets file attributes from the remote server.
///
internal SftpFileAttributes GetAttributes(string path)
{
var client = RequireClient();
return client.GetAttributes(path);
}
///
/// Sets file attributes on the remote server.
///
internal void SetAttributes(string path, SftpFileAttributes attrs)
{
var client = RequireClient();
client.SetAttributes(path, attrs);
}
// ═══════════════════════════════════════════════════════════════════
// INTERNALS
// ═══════════════════════════════════════════════════════════════════
private SftpClient RequireClient()
{
return _client ?? throw new InvalidOperationException(
"SFTP client is not connected. Call ConnectAsync() first.");
}
private Encoding ResolveEncoding()
{
try
{
return Encoding.GetEncoding(_options.Charset);
}
catch
{
return Encoding.UTF8;
}
}
}