using System.Text; namespace AIAssistantModule.Infrastructure.Helpers { public class FileAccessHelper { private static readonly Encoding DefaultEncoding = new UTF8Encoding(false); public async Task ReadFileAsync(string filePath, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("File path cannot be null or empty.", nameof(filePath)); if (!File.Exists(filePath)) throw new FileNotFoundException("File not found.", filePath); return await File.ReadAllTextAsync(filePath, DefaultEncoding, cancellationToken); } public async Task WriteFileAsync( string filePath, string content, bool backup = true, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("File path cannot be null or empty.", nameof(filePath)); if (content is null) throw new ArgumentNullException(nameof(content)); var directory = Path.GetDirectoryName(filePath); if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (backup && File.Exists(filePath)) { BackupFile(filePath); } await File.WriteAllTextAsync(filePath, content, DefaultEncoding, cancellationToken); } private void BackupFile(string filePath) { var timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff"); var backupPath = $"{filePath}.bak_{timestamp}"; File.Copy(filePath, backupPath, overwrite: false); } } }