forked from dexyfex/CodeWalker
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleKvpFile.cs
More file actions
100 lines (93 loc) · 2.99 KB
/
Copy pathSimpleKvpFile.cs
File metadata and controls
100 lines (93 loc) · 2.99 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
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeWalker.ModManager
{
public class SimpleKvpFile
{
public string FileName;
public string FilePath;
public bool FileExists;
public bool OnlySaveIfFileExists;
public Exception FileError;
public Dictionary<string, string> Items = new Dictionary<string, string>();
public SimpleKvpFile() { }
public SimpleKvpFile(string filePath, bool loadFile = false)
{
FilePath = filePath;
FileName = Path.GetFileName(filePath);
if (loadFile)
{
Load();
}
}
public virtual void Load()
{
Items.Clear();
FileExists = File.Exists(FilePath);
if (FileExists == false)
{
FileError = new Exception($"File not found: {FilePath}");
return;
}
try
{
var lines = File.ReadAllLines(FilePath);
if (lines == null) return;
foreach (var line in lines)
{
var tline = line?.Trim();
if (string.IsNullOrEmpty(tline)) continue;
var spi = tline.IndexOf(' ');
if (spi < 1) continue;
if (spi >= (tline.Length - 1)) continue;
var key = tline.Substring(0, spi).Trim().Replace("<SPACE>", " ");
var val = tline.Substring(spi + 1).Trim().Replace("<NEWLINE>", "\n");
if (string.IsNullOrEmpty(key)) continue;
if (string.IsNullOrEmpty(val)) continue;
Items[key] = val;
}
}
catch (Exception ex)
{
FileError = ex;
FileExists = false;
}
}
public virtual void Save()
{
if ((FileExists == false) && OnlySaveIfFileExists) return;
try
{
var sb = new StringBuilder();
foreach (var kvp in Items)
{
var key = kvp.Key?.Replace(" ", "<SPACE>");
var val = kvp.Value?.Replace("\n", "<NEWLINE>");
sb.AppendLine($"{key} {val}");
}
var str = sb.ToString();
File.WriteAllText(FilePath, str);
}
catch (Exception ex)
{
FileError = ex;
//FileExists = false;
}
}
public string GetItem(string key)
{
if (string.IsNullOrEmpty(key)) return null;
Items.TryGetValue(key, out var item);
return item;
}
public void SetItem(string key, string val)
{
if (string.IsNullOrEmpty(key)) return;
Items[key] = val;
}
}
}