From 95bd8fe37ff5b0d8599749060c814853c45c80f1 Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 2 Apr 2024 07:21:50 +0300 Subject: [PATCH] 20240402 --- anbs_cp/Classes/ActionState.cs | 19 ++--- anbs_cp/Classes/FileExtensions.cs | 31 -------- anbs_cp/Extensions/FileExtensions.cs | 113 +++++++++++++++++++++++++++ anbs_cp/anbs_cp.csproj | 2 +- demo/FileHashAndMimeTypeTest.cs | 4 +- 5 files changed, 127 insertions(+), 42 deletions(-) delete mode 100644 anbs_cp/Classes/FileExtensions.cs create mode 100644 anbs_cp/Extensions/FileExtensions.cs diff --git a/anbs_cp/Classes/ActionState.cs b/anbs_cp/Classes/ActionState.cs index f5121f7..9a08641 100644 --- a/anbs_cp/Classes/ActionState.cs +++ b/anbs_cp/Classes/ActionState.cs @@ -10,7 +10,7 @@ namespace anbs_cp.Classes; /* История версий Обновлено 2024.03.28 - * Все поля Errors, Warnings и Infos объеденены в одно Messages + * Все поля Errors, Warnings и Infos объеденины в одно Messages * В ActionStateMessage добавлен параметр, определяющий тип: MessageType Обновлено 2024.03.26 @@ -50,7 +50,7 @@ public class ActionState: ISerializable /// Метод для выбора всех значений для условия /// // ReSharper disable once StaticMemberInGenericType - public static readonly Func SelectAll = _ => true; + public static readonly Func SelectAll = static _ => true; #region Методы #region Очистка @@ -59,7 +59,7 @@ public class ActionState: ISerializable /// public void ClearErrors () { - Clear(message => message.MessageType == EActionStateMessageType.Error); + Clear(static message => message.MessageType == EActionStateMessageType.Error); } /// @@ -67,7 +67,7 @@ public class ActionState: ISerializable /// public void ClearWarnings () { - Clear(message => message.MessageType == EActionStateMessageType.Warning); + Clear(static message => message.MessageType == EActionStateMessageType.Warning); } /// @@ -75,7 +75,7 @@ public class ActionState: ISerializable /// public void ClearInfo () { - Clear(message => message.MessageType == EActionStateMessageType.Information); + Clear(static message => message.MessageType == EActionStateMessageType.Information); } /// @@ -177,17 +177,18 @@ public class ActionState: ISerializable list.AddRange(Messages); break; case EActionStatePrintArea.ErrorsAndWarnings: - list.AddRange(Messages.Where(message => + list.AddRange(Messages.Where(static message => message.MessageType is EActionStateMessageType.Error or EActionStateMessageType.Warning)); break; case EActionStatePrintArea.ErrorsOnly: - list.AddRange(Messages.Where(message => message.MessageType == EActionStateMessageType.Error)); + list.AddRange(Messages.Where(static message => message.MessageType == EActionStateMessageType.Error)); break; case EActionStatePrintArea.WarningsOnly: - list.AddRange(Messages.Where(message => message.MessageType == EActionStateMessageType.Warning)); + list.AddRange(Messages.Where(static message => message.MessageType == EActionStateMessageType.Warning)); break; case EActionStatePrintArea.InfosOnly: - list.AddRange(Messages.Where(message => message.MessageType == EActionStateMessageType.Information)); + list.AddRange(Messages.Where(static message => + message.MessageType == EActionStateMessageType.Information)); break; default: throw new ArgumentOutOfRangeException(nameof(area), area, null); diff --git a/anbs_cp/Classes/FileExtensions.cs b/anbs_cp/Classes/FileExtensions.cs deleted file mode 100644 index 9ee3bb8..0000000 --- a/anbs_cp/Classes/FileExtensions.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace anbs_cp.Classes; - -/// -/// Класс -- расширение для класса File -/// -public static class FileExtension -{ - /// - /// Получает MIME-тип файла - /// - /// Имя файла - /// MIME-тип файла - public static string MimeType (string filename) => - MimeTypes.GetMimeType(filename); - - /// - /// Размер файла в байтах - /// - /// Полное имя и путь к файлу - /// Размер файла в байтах - public static long FileSize (string fileName) => - new FileInfo(fileName).Length; - - /// - /// Получает хэш файла - /// - /// Имя файла - /// Хэш файла в формате - public static FileHash GetHash (string fileName) => - new(fileName); -} \ No newline at end of file diff --git a/anbs_cp/Extensions/FileExtensions.cs b/anbs_cp/Extensions/FileExtensions.cs new file mode 100644 index 0000000..9bbb493 --- /dev/null +++ b/anbs_cp/Extensions/FileExtensions.cs @@ -0,0 +1,113 @@ +using System.Text; + +using anbs_cp.Classes; + +namespace anbs_cp.Extensions; + +/// +/// Класс -- расширение для класса File +/// +public static class FileExtension +{ + /// + /// Получает MIME-тип файла + /// + /// Имя файла + /// MIME-тип файла + public static string MimeType (string filename) => + MimeTypes.GetMimeType(filename); + + /// + /// Размер файла в байтах + /// + /// Полное имя и путь к файлу + /// Размер файла в байтах + public static long FileSize (string fileName) => + new FileInfo(fileName).Length; + + /// + /// Получает хэш файла + /// + /// Имя файла + /// Хэш файла в формате + public static FileHash GetHash (string fileName) => + new(fileName); + + /// + /// Записывает данные в текстовый файл + /// + /// Тип данных + /// Данные + /// Имя файла + /// Нужно ли использовать кодировку UTF8 With BOM или UTF8 Without BOM + public static void Write (T data, string fileName, bool useUtf8WithBom = false) + { + // Кодировка + Encoding filEncoding = + useUtf8WithBom ? Encoding.UTF8 : new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + // Открываю файл для создания или перезаписи + using StreamWriter writer = new(new FileStream(fileName, FileMode.OpenOrCreate), filEncoding); + + // Записываю + writer.WriteLine(new NewtonsoftJsonSerializer().Serialize(data)); + } + + /// + /// Читает первую строку из текстового файла + /// + /// Имя файла + /// Нужно ли использовать кодировку UTF8 With BOM или UTF8 Without BOM + /// Тип выходных данных + /// Данные или null + public static T? Read (string fileName, bool useUtf8WithBom = false) + { + // Кодировка + Encoding filEncoding = + useUtf8WithBom ? Encoding.UTF8 : new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + // Открываю файл для чтения + using StreamReader reader = new(new FileStream(fileName, FileMode.Open), filEncoding); + + // Считываю первую запись + string serialized = reader.ReadLine() ?? "{}"; + + // Возвращаю конвертированный тип + return new NewtonsoftJsonSerializer().Deserialize(serialized); + } + + /// + /// Читает все строки из текстового файла + /// + /// Имя файла + /// Нужно ли использовать кодировку UTF8 With BOM или UTF8 Without BOM + /// Тип выходных данных + /// Список данных + public static IEnumerable ReadAll (string fileName, bool useUtf8WithBom = false) + { + // Создаю результат + List result = []; + + // Кодировка + Encoding filEncoding = + useUtf8WithBom ? Encoding.UTF8 : new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + // Открываю файл для чтения + using StreamReader reader = new(new FileStream(fileName, FileMode.Open), filEncoding); + + // Пока есть строки в файле + while (reader.ReadLine() is { } serialized) + { + // - десериализую их + T? data = new NewtonsoftJsonSerializer().Deserialize(serialized); + + // - и если они не нулевые + if (data is not null) + // -- то добавляю их в результат + result.Add(data); + } + + // Возвращаю полученный список + return result.AsEnumerable(); + } +} \ No newline at end of file diff --git a/anbs_cp/anbs_cp.csproj b/anbs_cp/anbs_cp.csproj index 430a23f..8063096 100644 --- a/anbs_cp/anbs_cp.csproj +++ b/anbs_cp/anbs_cp.csproj @@ -2,7 +2,7 @@ net8.0 - 2024.3.29 + 2024.4.02 Александр Бабаев Набор компонентов ANB Software Библиотека полезных методов языка C# diff --git a/demo/FileHashAndMimeTypeTest.cs b/demo/FileHashAndMimeTypeTest.cs index 6e28617..9b5da46 100644 --- a/demo/FileHashAndMimeTypeTest.cs +++ b/demo/FileHashAndMimeTypeTest.cs @@ -1,4 +1,6 @@ using anbs_cp.Classes; +using anbs_cp.Extensions; + // ReSharper disable LocalizableElement namespace demo; @@ -15,7 +17,7 @@ public sealed partial class FileHashAndMimeType: Form openFileDialog.ShowDialog(); } -private void GetFileHashAndMimeType() + private void GetFileHashAndMimeType () { if (string.IsNullOrEmpty(fileNameEdt.Text)) {