NoteMAUI/NoteContent/FileSaver.cs

83 lines
3.2 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NotesDataAnalyst.NoteContent
{
public class FileSaver : INotifyPropertyChanged
{
// Базовый путь, где будут храниться все заметки
private readonly string _basePath;
private ObservableCollection<string> _files;
// Коллекция для хранения путей к сохранённым файлам
public ObservableCollection<string> Files
{
get => _files;
private set
{
_files = value;
OnPropertyChanged(nameof(Files));
}
}
public FileSaver(string basePath)
{
// Устанавливаем базовый путь и инициализируем коллекцию файлов
_basePath = basePath;
Files = new ObservableCollection<string>();
}
// Создаёт путь к файлу на основе категории и заголовка
private string GenerateFilePath(Note note)
{
// Определяем путь для папки категории
string categoryFolder = Path.Combine(_basePath, note.Category);
// Создаём папку, если её ещё нет
Directory.CreateDirectory(categoryFolder);
// Преобразуем заголовок в имя файла, удаляя недопустимые символы
string fileName = SanitizeFileName(note.Title) + ".json";
// Полный путь к файлу
return Path.Combine(categoryFolder, fileName);
}
// Удаляет недопустимые символы из заголовка для имени файла
private string SanitizeFileName(string title)
{
// Заменяем символы, которые нельзя использовать в именах файлов, на подчёркивания
return Regex.Replace(title, @"[<>:""/\|?*]", "_");
}
public void SaveData(Note note)
{
// Если у заметки есть путь к файлу, обновляем существующий файл
string filePath = !string.IsNullOrEmpty(note.FilePath)
? note.FilePath
: GenerateFilePath(note);
string jsonString = JsonSerializer.Serialize(note);
File.WriteAllText(filePath, jsonString);
// Если это новая заметка, добавляем её путь в коллекцию
if (!Files.Contains(filePath))
{
Files.Add(filePath);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}