Notes
1using System;
2using System.Collections.Generic;
3using System.Collections.ObjectModel;
4using System.IO;
5using System.Linq;
6using System.Text;
7using System.Threading.Tasks;
8using Newtonsoft.Json;
9using ViewModel;
10
11namespace Model.Services
12{
13public static class NotesSerializer
14{
15/// <summary>
16/// Путь к – «Мои документы\Notes\notes.json».
17/// </summary>
18public static string MyDocumentsPath { get; set; } =
19Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
20+ @"\Notes\notes.json";
21
22public static void Serialize(List<NoteDTO>? notes)
23{
24if (!Directory.Exists(Path.GetDirectoryName(MyDocumentsPath)))
25Directory.CreateDirectory(Path.GetDirectoryName(MyDocumentsPath));
26using (StreamWriter writer = new StreamWriter(MyDocumentsPath))
27{
28writer.Write(JsonConvert.SerializeObject(notes));
29}
30}
31
32public static ObservableCollection<NoteViewModel>? Deserialize()
33{
34if (!Directory.Exists(Path.GetDirectoryName(MyDocumentsPath)))
35Directory.CreateDirectory(Path.GetDirectoryName(MyDocumentsPath));
36ObservableCollection<NoteViewModel>? contacts =
37new ObservableCollection<NoteViewModel>();
38try
39{
40using (StreamReader reader = new StreamReader(MyDocumentsPath))
41{
42contacts = JsonConvert.
43DeserializeObject<ObservableCollection<NoteViewModel>>(reader.ReadToEnd());
44}
45
46if (contacts == null) contacts = new ObservableCollection<NoteViewModel>();
47}
48catch (FileNotFoundException e)
49{
50return contacts;
51}
52
53return contacts;
54}
55}
56}
57