| | | 1 | | using System.IO.Abstractions; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace ToolCore; |
| | | 5 | | |
| | | 6 | | public class FileUtils |
| | | 7 | | { |
| | | 8 | | private readonly IFileSystem _fileSystem; |
| | | 9 | | |
| | | 10 | | // Конструктор по умолчанию использует реальную ОС, а для тестов мы сможем передать мок |
| | 20 | 11 | | public FileUtils(IFileSystem? fileSystem = null) |
| | | 12 | | { |
| | 20 | 13 | | _fileSystem = fileSystem ?? new FileSystem(); |
| | 20 | 14 | | } |
| | | 15 | | |
| | | 16 | | public async Task<(List<string> Lines, Encoding Encoding, string Separator, bool HasFinalNewLine)> ReadFileWithMetad |
| | | 17 | | string filepath, CancellationToken cancellationToken = default) |
| | | 18 | | { |
| | 20 | 19 | | var lines = new List<string>(); |
| | 20 | 20 | | Encoding encoding = new UTF8Encoding(false); |
| | 20 | 21 | | var separator = Environment.NewLine; |
| | 20 | 22 | | var hasFinalNewLine = false; |
| | | 23 | | |
| | 20 | 24 | | if (!_fileSystem.File.Exists(filepath)) // Используем интерфейс |
| | | 25 | | { |
| | 2 | 26 | | return (lines, encoding, separator, hasFinalNewLine); |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | // Ограничиваем максимальный размер |
| | 18 | 30 | | var fileInfo = _fileSystem.FileInfo.New(filepath); |
| | | 31 | | const long maxAllowedSize = 2 * 1024 * 1024; // 2 МБ и то много |
| | 18 | 32 | | if (fileInfo.Length > maxAllowedSize) |
| | | 33 | | { |
| | | 34 | | // Файл слишком большой для этого метода, возвращаем пустой результат |
| | 0 | 35 | | return (lines, encoding, separator, hasFinalNewLine); |
| | | 36 | | } |
| | | 37 | | |
| | | 38 | | // ПРОВЕРКА НА БИНАРНОСТЬ: Заглядываем в начало файла |
| | 18 | 39 | | using (var fsCheck = _fileSystem.FileStream.New(filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, |
| | | 40 | | { |
| | 18 | 41 | | var sampleBuffer = new byte[1024]; |
| | 18 | 42 | | var bytesRead = await fsCheck.ReadAsync(sampleBuffer, 0, sampleBuffer.Length, cancellationToken).ConfigureAw |
| | | 43 | | |
| | 1104 | 44 | | for (var i = 0; i < bytesRead; i++) |
| | | 45 | | { |
| | 536 | 46 | | if (sampleBuffer[i] == 0x00) // Обнаружен Null-символ -> это бинарный файл |
| | | 47 | | { |
| | | 48 | | // Пропускаем чтение бинарного файла |
| | 0 | 49 | | return (lines, encoding, separator, hasFinalNewLine); |
| | | 50 | | } |
| | | 51 | | } |
| | 16 | 52 | | } |
| | | 53 | | |
| | | 54 | | // Читаем текстовый файл |
| | | 55 | | string fullText; |
| | 16 | 56 | | using (var fs = _fileSystem.FileStream.New(filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileO |
| | 16 | 57 | | using (var reader = new StreamReader(fs, encoding, detectEncodingFromByteOrderMarks: true)) |
| | | 58 | | { |
| | 16 | 59 | | fullText = await reader.ReadToEndAsync().ConfigureAwait(false); |
| | 16 | 60 | | encoding = reader.CurrentEncoding; |
| | 16 | 61 | | } |
| | | 62 | | |
| | 16 | 63 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 64 | | |
| | 16 | 65 | | if (string.IsNullOrEmpty(fullText)) |
| | | 66 | | { |
| | 0 | 67 | | return (lines, encoding, separator, hasFinalNewLine); |
| | | 68 | | } |
| | | 69 | | |
| | | 70 | | // Определение разделителей |
| | 24 | 71 | | if (fullText.Contains("\r\n")) separator = "\r\n"; |
| | 12 | 72 | | else if (fullText.Contains("\n")) separator = "\n"; |
| | 4 | 73 | | else if (fullText.Contains("\r")) separator = "\r"; |
| | | 74 | | |
| | 16 | 75 | | if (fullText.EndsWith("\n") || fullText.EndsWith("\r")) |
| | | 76 | | { |
| | 6 | 77 | | hasFinalNewLine = true; |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | // Парсинг строк |
| | 16 | 81 | | var splitSeparators = new[] { "\r\n", "\r", "\n" }; |
| | 16 | 82 | | var allLines = fullText.Split(splitSeparators, StringSplitOptions.None); |
| | | 83 | | |
| | 16 | 84 | | if (allLines.Length > 0) |
| | | 85 | | { |
| | 16 | 86 | | lines.AddRange(allLines); |
| | | 87 | | |
| | 16 | 88 | | if (hasFinalNewLine && lines.Count > 0 && string.IsNullOrEmpty(lines[lines.Count - 1])) |
| | | 89 | | { |
| | 6 | 90 | | lines.RemoveAt(lines.Count - 1); |
| | | 91 | | } |
| | | 92 | | } |
| | | 93 | | |
| | 16 | 94 | | return (lines, encoding, separator, hasFinalNewLine); |
| | 18 | 95 | | } |
| | | 96 | | |
| | | 97 | | public async Task SaveFileAsync(string filepath, List<string> lines, Encoding encoding, string separator, bool hasFi |
| | | 98 | | { |
| | 12 | 99 | | var content = string.Join(separator, lines); |
| | | 100 | | |
| | 12 | 101 | | if (hasFinalNewLine) |
| | | 102 | | { |
| | 6 | 103 | | content += separator; |
| | | 104 | | } |
| | | 105 | | |
| | 12 | 106 | | var directory = _fileSystem.Path.GetDirectoryName(filepath); |
| | 12 | 107 | | if (!string.IsNullOrEmpty(directory) && !_fileSystem.Directory.Exists(directory)) |
| | | 108 | | { |
| | 0 | 109 | | _fileSystem.Directory.CreateDirectory(directory); |
| | | 110 | | } |
| | | 111 | | |
| | | 112 | | // Создаем файл через фабрику интерфейса |
| | 12 | 113 | | using var fs = _fileSystem.FileStream.New(filepath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, Fil |
| | 12 | 114 | | using var writer = new StreamWriter(fs, encoding); |
| | 12 | 115 | | await writer.WriteAsync(content).ConfigureAwait(false); |
| | 12 | 116 | | } |
| | | 117 | | } |