-
Notifications
You must be signed in to change notification settings - Fork 0
/
IniFile.cs
658 lines (567 loc) · 15.5 KB
/
IniFile.cs
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
// **************************
// *** IniFile class V1.0 ***
// **************************
// *** (C)2009 S.T.A. snc ***
// **************************
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace ImportWLK
{
internal class IniFile
{
#region "Declarations"
// *** Lock for thread-safe access to file and local cache ***
private readonly object m_Lock = new();
// *** File name ***
private string m_FileName = null;
internal string FileName
{
get
{
return m_FileName;
}
}
// *** Lazy loading flag ***
private bool m_Lazy = false;
// *** Local cache ***
private readonly Dictionary<string, Dictionary<string, string>> m_Sections = [];
// *** Local cache modified flag ***
private bool m_CacheModified = false;
internal static readonly string[] quoteCommaQuote = ["\",\""];
#endregion
#region "Methods"
// *** Constructor ***
public IniFile(string FileName)
{
Initialize(FileName, false);
}
public IniFile(string FileName, bool Lazy)
{
Initialize(FileName, Lazy);
}
// Readonly - from string
public IniFile()
{
m_Lazy = false;
}
// *** Initialization ***
private void Initialize(string FileName, bool Lazy)
{
m_FileName = FileName;
m_Lazy = Lazy;
if (!m_Lazy) Refresh();
}
// Load a supplied string rather than read from file
internal void LoadString(string[] inputStr)
{
// *** Clear local cache ***
m_Sections.Clear();
// *** Read up the array content ***
Dictionary<string, string> CurrentSection = null;
foreach (var line in inputStr)
{
var s = line.Trim();
// *** Check for section names ***
if (s.StartsWith('[') && s.EndsWith(']'))
{
if (s.Length > 2)
{
string SectionName = s[1..^1];
// *** Only first occurrence of a section is loaded ***
if (m_Sections.ContainsKey(SectionName))
{
CurrentSection = null;
}
else
{
CurrentSection = [];
m_Sections.Add(SectionName, CurrentSection);
}
}
}
else if (CurrentSection != null)
{
// *** Check for key+value pair ***
int i;
if ((i = s.IndexOf('=')) > 0)
{
// It's a value
int j = s.Length - i - 1;
string Key = s[..i].Trim();
if (Key.Length > 0 && !CurrentSection.ContainsKey(Key))
{
// *** Only first occurrence of a key is loaded ***
string Value = (j > 0) ? (s.Substring(i + 1, j).Trim()) : ("");
CurrentSection.Add(Key, Value);
}
}
}
}
}
// *** Read file contents into local cache ***
internal void Refresh()
{
lock (m_Lock)
{
FileStream fs = null;
StreamReader sr = null;
try
{
// *** Clear local cache ***
m_Sections.Clear();
// *** Open the INI file ***
if (File.Exists(m_FileName))
{
fs = new FileStream(m_FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
sr = new StreamReader(fs);
}
else
{
return;
}
// *** Read up the file content ***
Dictionary<string, string> CurrentSection = null;
string s;
while ((s = sr.ReadLine()) != null)
{
s = s.Trim();
// *** Check for section names ***
if (s.StartsWith('[') && s.EndsWith(']'))
{
if (s.Length > 2)
{
string SectionName = s[1..^1];
// *** Only first occurrence of a section is loaded ***
if (m_Sections.ContainsKey(SectionName))
{
CurrentSection = null;
}
else
{
CurrentSection = [];
m_Sections.Add(SectionName, CurrentSection);
}
}
}
else if (CurrentSection != null)
{
// *** Check for key+value pair ***
int i;
if (s.StartsWith('#'))
{
// It's a comment
// *** Only first occurrence of a key is loaded ***
CurrentSection.TryAdd(s, "");
}
else if ((i = s.IndexOf('=')) > 0)
{
// It's a value
int j = s.Length - i - 1;
string Key = s[..i].Trim();
if (Key.Length > 0 && !CurrentSection.ContainsKey(Key))
{
// *** Only first occurrence of a key is loaded ***
string Value = (j > 0) ? (s.Substring(i + 1, j).Trim()) : ("");
CurrentSection.Add(Key, Value);
}
}
}
}
}
finally
{
// *** Cleanup: close file ***
if (sr != null) sr.Close();
if (fs != null) fs.Close();
}
}
}
// *** Flush local cache content ***
internal void Flush()
{
lock (m_Lock)
{
// *** If local cache was not modified, exit ***
if (!m_CacheModified) return;
var success = false;
var retries = 1;
do
{
try
{
// *** Open the file ***
using (StreamWriter sw = new StreamWriter(m_FileName))
{
sw.WriteLine($"#Last updated: {DateTime.Now:G}");
// *** Cycle on all sections ***
bool First = false;
foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Sections)
{
Dictionary<string, string> Section = SectionPair.Value;
if (First) sw.WriteLine();
First = true;
// *** Write the section name ***
sw.Write('[');
sw.Write(SectionPair.Key);
sw.WriteLine(']');
// *** Cycle on all key+value pairs in the section ***
foreach (KeyValuePair<string, string> ValuePair in Section)
{
// *** Write the key+value pair ***
sw.Write(ValuePair.Key);
if (!ValuePair.Key.StartsWith('#'))
{
sw.Write('=');
sw.Write(ValuePair.Value);
}
sw.WriteLine();
}
}
}
success = true;
m_CacheModified = false;
}
catch (IOException ex)
{
if (ex.HResult == -2147024864) // 0x80070020
{
retries--;
System.Threading.Thread.Sleep(250);
}
else
{
throw;
}
}
} while (!success && retries >= 0);
}
}
// *** Read a value from local cache ***
// *** Insert or modify a value in local cache ***
internal bool ValueExists(string SectionName, string Key)
{
// *** Lazy loading ***
if (m_Lazy)
{
m_Lazy = false;
Refresh();
}
lock (m_Lock)
{
// *** Check if the section exists ***
Dictionary<string, string> Section;
if (!m_Sections.TryGetValue(SectionName, out Section)) return false;
// *** Check if the key exists ***
string Value;
if (Section.TryGetValue(Key, out Value))
return true;
else
return false;
}
}
internal void DeleteValue(string SectionName, string Key)
{
// *** Lazy loading ***
if (m_Lazy)
{
m_Lazy = false;
Refresh();
}
lock (m_Lock)
{
// *** Check if the section exists ***
Dictionary<string, string> Section;
if (!m_Sections.TryGetValue(SectionName, out Section)) return;
// *** Check if the key exists ***
string Value;
if (Section.TryGetValue(Key, out Value))
{
m_CacheModified = true;
Section.Remove(Key);
}
}
}
// *** Encode byte array ***
private static string EncodeByteArray(byte[] Value)
{
if (Value == null) return null;
StringBuilder sb = new StringBuilder();
foreach (byte b in Value)
{
string hex = Convert.ToString(b, 16);
int l = hex.Length;
if (l > 2)
{
sb.Append(hex.AsSpan(l - 2, 2));
}
else
{
if (l < 2) sb.Append('0');
sb.Append(hex);
}
}
return sb.ToString();
}
// *** Decode byte array ***
private static byte[] DecodeByteArray(string Value)
{
if (Value == null) return [];
int l = Value.Length;
if (l < 2) return [];
l /= 2;
byte[] Result = new byte[l];
for (int i = 0; i < l; i++) Result[i] = Convert.ToByte(Value.Substring(i * 2, 2), 16);
return Result;
}
// *** Encode bool array
private static string EncodeBoolArray(bool[] Value)
{
if (Value == null) return null;
StringBuilder sb = new StringBuilder();
foreach (bool b in Value)
{
sb.Append(b ? "1," : "0,");
}
if (sb[^1] == ',')
sb.Length--;
return sb.ToString();
}
// *** Decode bool array
private static bool[] DecodeBoolArray(string Value, int Length)
{
if (Value == null) return [];
var arr = Value.Split(',');
var ret = new bool[Math.Max(arr.Length, Length)];
for (var i = 0; i < ret.Length; i++)
{
ret[i] = Convert.ToBoolean(Convert.ToInt32(arr[i]));
}
return ret;
}
// *** Encode string array - very basic, no escaped quotes allowed
private static string EncodeStringArray(string[] Value)
{
if (Value == null) return null;
StringBuilder sb = new StringBuilder();
foreach (string b in Value)
{
sb.Append($"\"{b}\",");
}
if (sb[^1] == ',')
sb.Length--;
return sb.ToString();
}
// *** Decode string array - very basic, no escaped quotes allowed
private static string[] DecodeStringArray(string Value)
{
if (Value == null) return [];
var x = Value[1..^1];
return x.Split(quoteCommaQuote, StringSplitOptions.None);
}
private static string EncodeIntArray(int[] Value)
{
if (Value == null) return null;
return string.Join(",", Value);
}
// *** Decode string array - very basic, no escaped quotes allowed
private static int[] DecodeIntArray(string Value, int Length)
{
if (Value == null) return [];
var arr = Value.Split(',');
var ret = new int[Math.Max(arr.Length, Length)];
for (var i = 0; i < ret.Length; i++)
{
ret[i] = Convert.ToInt32(arr[i]);
}
return ret;
}
// *** Getters for various types ***
internal string GetValue(string SectionName, string Key, string DefaultValue)
{
// *** Lazy loading ***
if (m_Lazy)
{
m_Lazy = false;
Refresh();
}
lock (m_Lock)
{
// *** Check if the section exists ***
Dictionary<string, string> Section;
if (!m_Sections.TryGetValue(SectionName, out Section)) return DefaultValue;
// *** Check if the key exists ***
string Value;
if (!Section.TryGetValue(Key, out Value)) return DefaultValue;
// *** Check if the value is blank ***
if (string.IsNullOrWhiteSpace(Value)) return DefaultValue;
// *** Return the found value ***
return Value;
}
}
internal bool GetValue(string SectionName, string Key, bool DefaultValue)
{
string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(System.Globalization.CultureInfo.InvariantCulture));
int Value;
if (int.TryParse(StringValue, out Value)) return (Value != 0);
return DefaultValue;
}
internal int GetValue(string SectionName, string Key, int DefaultValue, int MinValue = int.MinValue, int MaxValue = int.MaxValue)
{
string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture));
int Value;
if (int.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value))
{
if (Value < MinValue) return MinValue;
if (Value > MaxValue) return MaxValue;
return Value;
}
return DefaultValue;
}
internal double GetValue(string SectionName, string Key, double DefaultValue, double MinValue = double.MinValue, double MaxValue = double.MaxValue)
{
string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture));
double Value;
if (double.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value))
{
if (Value < MinValue) return MinValue;
if (Value > MaxValue) return MaxValue;
return Value;
}
return DefaultValue;
}
internal decimal GetValue(string SectionName, string Key, decimal DefaultValue, decimal MinValue = decimal.MinValue, decimal MaxValue = decimal.MaxValue)
{
string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture));
decimal Value;
if (decimal.TryParse(StringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out Value))
{
if (Value < MinValue) return MinValue;
if (Value > MaxValue) return MaxValue;
return Value;
}
return DefaultValue;
}
internal byte[] GetValue(string SectionName, string Key, byte[] DefaultValue)
{
string StringValue = GetValue(SectionName, Key, EncodeByteArray(DefaultValue));
try
{
return DecodeByteArray(StringValue);
}
catch (FormatException)
{
return DefaultValue;
}
}
internal bool[] GetValue(string SectionName, string Key, bool[] DefaultValue)
{
string StringValue = GetValue(SectionName, Key, EncodeBoolArray(DefaultValue));
try
{
return DecodeBoolArray(StringValue, DefaultValue.Length);
}
catch (FormatException)
{
return DefaultValue;
}
}
internal string[] GetValue(string SectionName, string Key, string[] DefaultValue)
{
string StringValue = GetValue(SectionName, Key, EncodeStringArray(DefaultValue));
try
{
return DecodeStringArray(StringValue);
}
catch (FormatException)
{
return DefaultValue;
}
}
internal int[] GetValue(string SectionName, string Key, int[] DefaultValue)
{
string StringValue = GetValue(SectionName, Key, EncodeIntArray(DefaultValue));
try
{
return DecodeIntArray(StringValue, DefaultValue.Length);
}
catch (FormatException)
{
return DefaultValue;
}
}
internal DateTime GetValue(string SectionName, string Key, DateTime DefaultValue)
{
string StringValue = GetValue(SectionName, Key, DefaultValue.ToString(CultureInfo.InvariantCulture));
DateTime Value;
if (DateTime.TryParse(StringValue, CultureInfo.InvariantCulture, out Value)) return Value;
return DefaultValue;
}
// *** Setters for various types ***
internal void SetValue(string SectionName, string Key, string Value)
{
// *** Lazy loading ***
if (m_Lazy)
{
m_Lazy = false;
Refresh();
}
lock (m_Lock)
{
// *** Flag local cache modification ***
m_CacheModified = true;
// *** Check if the section exists ***
Dictionary<string, string> Section;
if (!m_Sections.TryGetValue(SectionName, out Section))
{
// *** If it doesn't, add it ***
Section = [];
m_Sections.Add(SectionName, Section);
}
// *** Modify the value ***
Section.Remove(Key);
Section.Add(Key, Value);
}
}
internal void SetValue(string SectionName, string Key, bool Value)
{
SetValue(SectionName, Key, (Value) ? ("1") : ("0"));
}
internal void SetValue(string SectionName, string Key, int Value)
{
SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture));
}
internal void SetValue(string SectionName, string Key, double Value)
{
SetValue(SectionName, Key, Value.ToString("G17", CultureInfo.InvariantCulture));
}
internal void SetValue(string SectionName, string Key, decimal Value)
{
SetValue(SectionName, Key, Value.ToString(CultureInfo.InvariantCulture));
}
internal void SetValue(string SectionName, string Key, byte[] Value)
{
SetValue(SectionName, Key, EncodeByteArray(Value));
}
internal void SetValue(string SectionName, string Key, bool[] Value)
{
SetValue(SectionName, Key, EncodeBoolArray(Value));
}
internal void SetValue(string SectionName, string Key, string[] Value)
{
SetValue(SectionName, Key, EncodeStringArray(Value));
}
internal void SetValue(string SectionName, string Key, int[] Value)
{
SetValue(SectionName, Key, EncodeIntArray(Value));
}
internal void SetValue(string SectionName, string Key, DateTime Value)
{
// write datetimes in ISO 8601 ("sortable")
SetValue(SectionName, Key, Value.ToString("s"));
}
#endregion
}
}