-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRecentFileManager.cs
More file actions
91 lines (74 loc) · 2.46 KB
/
RecentFileManager.cs
File metadata and controls
91 lines (74 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
namespace NMEA2000Analyzer
{
public class RecentFileEntry
{
public required string FilePath { get; set; }
public DateTime LastOpened { get; set; }
}
public static class RecentFilesManager
{
private const int MaxRecentFiles = 10;
private static readonly string BaseFolder =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"NMEA2000Analyzer");
private static readonly string FilePath =
Path.Combine(BaseFolder, "recent-files.json");
private static List<RecentFileEntry> _cache;
public static List<RecentFileEntry> Load()
{
if (_cache != null)
return _cache;
if (!File.Exists(FilePath))
{
_cache = new List<RecentFileEntry>();
return _cache;
}
try
{
var json = File.ReadAllText(FilePath);
_cache = JsonSerializer.Deserialize<List<RecentFileEntry>>(json)
?? new List<RecentFileEntry>();
}
catch
{
_cache = new List<RecentFileEntry>();
}
return _cache;
}
public static void RegisterFileOpen(string path)
{
var list = Load();
var existing = list.FirstOrDefault(x =>
x.FilePath.Equals(path, StringComparison.OrdinalIgnoreCase));
if (existing != null)
{
existing.LastOpened = DateTime.Now;
}
else
{
list.Insert(0, new RecentFileEntry
{
FilePath = path,
LastOpened = DateTime.Now
});
}
_cache = list
.OrderByDescending(x => x.LastOpened)
.Take(MaxRecentFiles)
.ToList();
Save();
}
private static void Save()
{
Directory.CreateDirectory(BaseFolder);
var json = JsonSerializer.Serialize(_cache,
new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(FilePath, json);
}
}
}