|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Text.Json; |
| 5 | + |
| 6 | +namespace FileSyncLibNet.Commons |
| 7 | +{ |
| 8 | + internal class RemoteState : IDisposable |
| 9 | + { |
| 10 | + public Dictionary<string, FileInfo2> FileInfos { get; set; } |
| 11 | + public string Filename { get; private set; } |
| 12 | + private static readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions |
| 13 | + { |
| 14 | + WriteIndented = true |
| 15 | + }; |
| 16 | + public RemoteState(string name) |
| 17 | + { |
| 18 | + Filename = $"RemoteState_{name}.json"; |
| 19 | + FileInfos = LoadFromFile(Filename); |
| 20 | + } |
| 21 | + public FileInfo2 GetFileInfo(string path) |
| 22 | + { |
| 23 | + if (FileInfos.ContainsKey(path)) |
| 24 | + return FileInfos[path]; |
| 25 | + |
| 26 | + return new FileInfo2(path, false) |
| 27 | + { |
| 28 | + LastWriteTime = DateTime.MinValue, |
| 29 | + Length = 0 |
| 30 | + }; |
| 31 | + } |
| 32 | + public void SetFileInfo(string path, FileInfo2 fileInfo) |
| 33 | + { |
| 34 | + if (FileInfos.ContainsKey(path)) |
| 35 | + { |
| 36 | + FileInfos[path] = fileInfo; |
| 37 | + } |
| 38 | + else |
| 39 | + FileInfos.Add(path, fileInfo); |
| 40 | + |
| 41 | + SaveToFile(Filename, FileInfos); |
| 42 | + } |
| 43 | + public void RemoveFileInfo(string path) |
| 44 | + { |
| 45 | + if (FileInfos.ContainsKey(path)) |
| 46 | + { |
| 47 | + FileInfos.Remove(path); |
| 48 | + } |
| 49 | + SaveToFile(Filename, FileInfos); |
| 50 | + } |
| 51 | + private static Dictionary<string, FileInfo2> LoadFromFile(string filename) |
| 52 | + { |
| 53 | + if (File.Exists(filename)) |
| 54 | + { |
| 55 | + try |
| 56 | + { |
| 57 | + var fileContent = File.ReadAllText(filename); |
| 58 | + var fileInfos = JsonSerializer.Deserialize<Dictionary<string, FileInfo2>>(fileContent); |
| 59 | + return fileInfos; |
| 60 | + } |
| 61 | + catch |
| 62 | + { |
| 63 | + return new Dictionary<string, FileInfo2>(); |
| 64 | + } |
| 65 | + } |
| 66 | + return new Dictionary<string, FileInfo2>(); |
| 67 | + } |
| 68 | + |
| 69 | + private static void SaveToFile(string filename, Dictionary<string, FileInfo2> fileInfos) |
| 70 | + { |
| 71 | + try |
| 72 | + { |
| 73 | + var fileContent = JsonSerializer.Serialize(fileInfos, jsonOptions); |
| 74 | + File.WriteAllText(filename, fileContent); |
| 75 | + } |
| 76 | + catch |
| 77 | + { |
| 78 | + |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + public void Dispose() |
| 83 | + { |
| 84 | + FileInfos.Clear(); |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments