-
Notifications
You must be signed in to change notification settings - Fork 0
/
IniFile.cs
719 lines (602 loc) · 26.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
// Rampastring's INI parser
// http://www.moddb.com/members/rampastring
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Text;
namespace Rampastring.Tools
{
/// <summary>
/// A class for parsing, handling and writing INI files.
/// </summary>
public class IniFile : IIniFile
{
private const string TextBlockBeginIdentifier = "$$$TextBlockBegin$$$";
private const string TextBlockEndIdentifier = "$$$TextBlockEnd$$$";
#region Static methods
/// <summary>
/// Consolidates two INI files, adding all of the second INI file's contents
/// to the first INI file. In case conflicting keys are found, the second
/// INI file takes priority.
/// </summary>
/// <param name="firstIni">The first INI file.</param>
/// <param name="secondIni">The second INI file.</param>
public static void ConsolidateIniFiles(IniFile firstIni, IniFile secondIni)
{
List<string> sections = secondIni.GetSections();
foreach (string section in sections)
{
List<string> sectionKeys = secondIni.GetSectionKeys(section);
foreach (string key in sectionKeys)
{
firstIni.SetStringValue(section, key, secondIni.GetStringValue(section, key, String.Empty));
}
}
}
#endregion
/// <summary>
/// Creates a new INI file instance.
/// </summary>
public IniFile() { }
/// <summary>
/// Creates a new INI file instance and parses it.
/// </summary>
/// <param name="filePath">The path of the INI file.</param>
public IniFile(string filePath)
{
FileName = filePath;
Parse();
}
/// <summary>
/// Creates a new INI file instance and parses it.
/// </summary>
/// <param name="filePath">The path of the INI file.</param>
/// <param name="encoding">The encoding of the INI file. Default for UTF-8.</param>
public IniFile(string filePath, Encoding encoding)
{
FileName = filePath;
Encoding = encoding;
Parse();
}
/// <summary>
/// Creates a new INI file instance and parses it.
/// </summary>
/// <param name="stream">The stream to read the INI file from.</param>
public IniFile(Stream stream)
{
ParseIniFile(stream);
}
/// <summary>
/// Creates a new INI file instance and parses it.
/// </summary>
/// <param name="stream">The stream to read the INI file from.</param>
/// <param name="encoding">The encoding of the INI file. Default for UTF-8.</param>
public IniFile(Stream stream, Encoding encoding)
{
Encoding = encoding;
ParseIniFile(stream, encoding);
}
public string FileName { get; set; }
public Encoding Encoding { get; set; } = new UTF8Encoding(false);
/// <summary>
/// Gets or sets a value that determines whether the parser should only parse
/// pre-determined (via <see cref="AddSection(string)"/>) sections or all sections in the INI file.
/// </summary>
public bool AllowNewSections { get; set; } = true;
/// <summary>
/// Comment line to write to the INI file when it's written.
/// </summary>
public string Comment { get; set; }
protected List<IniSection> Sections = new List<IniSection>();
private int _lastSectionIndex = 0;
public void Parse()
{
//FileInfo fileInfo = SafePath.GetFile(FileName);
FileInfo fileInfo = new FileInfo(FileName);
if (!fileInfo.Exists)
return;
FileStream stream = fileInfo.OpenRead();
ParseIniFile(stream);
}
/// <summary>
/// Clears all data from this IniFile instance and then re-parses the input INI file.
/// </summary>
public void Reload()
{
_lastSectionIndex = 0;
Sections.Clear();
Parse();
}
private void ParseIniFile(Stream stream, Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding;
using (var reader = new StreamReader(stream, encoding))
{
int currentSectionId = -1;
string currentLine = string.Empty;
while (!reader.EndOfStream)
{
currentLine = reader.ReadLine();
int commentStartIndex = currentLine.IndexOf(';');
if (commentStartIndex > -1)
currentLine = currentLine.Substring(0, commentStartIndex);
if (string.IsNullOrWhiteSpace(currentLine))
continue;
if (currentLine[0] == '[')
{
int sectionNameEndIndex = currentLine.IndexOf(']');
if (sectionNameEndIndex == -1)
throw new IniParseException("Invalid INI section definition: " + currentLine);
string sectionName = currentLine.Substring(1, sectionNameEndIndex - 1);
int index = Sections.FindIndex(c => c.SectionName == sectionName);
if (index > -1)
{
currentSectionId = index;
}
else if (AllowNewSections)
{
Sections.Add(new IniSection(sectionName));
currentSectionId = Sections.Count - 1;
}
else
currentSectionId = -1;
continue;
}
if (currentSectionId == -1)
continue;
int equalsIndex = currentLine.IndexOf('=');
if (equalsIndex == -1)
{
Sections[currentSectionId].AddOrReplaceKey(currentLine.Trim(), string.Empty);
}
else
{
string value = currentLine.Substring(equalsIndex + 1).Trim();
if (value == TextBlockBeginIdentifier)
{
value = ReadTextBlock(reader);
}
Sections[currentSectionId].AddOrReplaceKey(currentLine.Substring(0, equalsIndex).Trim(),
value);
}
}
//ApplyBaseIni();
}
}
private string ReadTextBlock(StreamReader reader)
{
StringBuilder stringBuilder = new StringBuilder();
while (true)
{
if (reader.EndOfStream)
{
throw new IniParseException("Encountered end-of-file while " +
"reading text block. Text block is not terminated properly.");
}
string line = reader.ReadLine().Trim();
if (line.Trim() == TextBlockEndIdentifier)
break;
stringBuilder.Append(line + Environment.NewLine);
}
if (stringBuilder.Length > 0)
{
stringBuilder.Remove(stringBuilder.Length - Environment.NewLine.Length,
Environment.NewLine.Length);
}
return stringBuilder.ToString();
}
/*
protected virtual void ApplyBaseIni()
{
string basedOn = GetStringValue("INISystem", "BasedOn", String.Empty);
if (!String.IsNullOrEmpty(basedOn))
{
// Consolidate with the INI file that this INI file is based on
string path = SafePath.CombineFilePath(SafePath.GetFileDirectoryName(FileName), basedOn);
IniFile baseIni = new IniFile(path);
ConsolidateIniFiles(baseIni, this);
Sections = baseIni.Sections;
}
}
*/
/// <summary>
/// Writes the INI file to the path that was
/// given to the instance on creation.
/// </summary>
public void WriteIniFile()
{
WriteIniFile(FileName);
}
/// <summary>
/// Writes the INI file to a specified stream.
/// </summary>
/// <param name="stream">The stream to write the INI file to.</param>
public void WriteIniStream(Stream stream)
{
WriteIniStream(stream, Encoding);
}
/// <summary>
/// Writes the INI file to a specified stream.
/// </summary>
/// <param name="stream">The stream to read the INI file from.</param>
/// <param name="encoding">The encoding of the INI file. Default for UTF-8.</param>
public void WriteIniStream(Stream stream, Encoding encoding)
{
using(StreamWriter sw = new StreamWriter(stream, encoding))
{
if (!string.IsNullOrWhiteSpace(Comment))
{
sw.WriteLine("; " + Comment);
sw.WriteLine();
}
foreach (IniSection section in Sections)
{
sw.Write("[" + section.SectionName + "]\r\n");
foreach (var kvp in section.Keys)
{
sw.Write(kvp.Key + "=" + kvp.Value + "\r\n");
}
sw.Write("\r\n");
}
sw.Write("\r\n");
}
}
/// <summary>
/// Writes the INI file's contents to the specified path.
/// </summary>
/// <param name="filePath">The path of the file to write to.</param>
public void WriteIniFile(string filePath)
{
//FileInfo fileInfo = SafePath.GetFile(filePath);
FileInfo fileInfo = new FileInfo(FileName);
if (fileInfo.Exists)
fileInfo.Delete();
using (var stream = fileInfo.OpenWrite())
{
WriteIniStream(stream);
}
}
/// <summary>
/// Creates and adds a section into the INI file.
/// </summary>
/// <param name="sectionName">The name of the section to add.</param>
public void AddSection(string sectionName)
{
Sections.Add(new IniSection(sectionName));
}
/// <summary>
/// Adds a section into the INI file.
/// </summary>
/// <param name="section">The section to add.</param>
public void AddSection(IniSection section)
{
Sections.Add(section);
}
/// <summary>
/// Removes the given section from the INI file.
/// Uses case-insensitive string comparison when looking for the section.
/// </summary>
/// <param name="sectionName">The name of the section to remove.</param>
public void RemoveSection(string sectionName)
{
int index = Sections.FindIndex(section =>
section.SectionName.Equals(sectionName,
StringComparison.InvariantCultureIgnoreCase));
if (index > -1)
Sections.RemoveAt(index);
}
/// <summary>
/// Moves a section's position to the first place in the INI file's section list.
/// </summary>
/// <param name="sectionName">The name of the INI section to move.</param>
public void MoveSectionToFirst(string sectionName)
{
int index = Sections.FindIndex(s => s.SectionName == sectionName);
if (index == -1)
return;
IniSection section = Sections[index];
Sections.RemoveAt(index);
Sections.Insert(0, section);
}
/// <summary>
/// Erases all existing keys of a section.
/// Does nothing if the section does not exist.
/// </summary>
/// <param name="sectionName">The name of the section.</param>
public void EraseSectionKeys(string sectionName)
{
int index = Sections.FindIndex(s => s.SectionName == sectionName);
if (index == -1)
return;
Sections[index].Keys.Clear();
}
/// <summary>
/// Combines two INI sections, with the second section overriding
/// in case conflicting keys are present. The combined section
/// then over-writes the second section.
/// </summary>
/// <param name="firstSectionName">The name of the first INI section.</param>
/// <param name="secondSectionName">The name of the second INI section.</param>
public void CombineSections(string firstSectionName, string secondSectionName)
{
int firstIndex = Sections.FindIndex(s => s.SectionName == firstSectionName);
if (firstIndex == -1)
return;
int secondIndex = Sections.FindIndex(s => s.SectionName == secondSectionName);
if (secondIndex == -1)
return;
IniSection firstSection = Sections[firstIndex];
IniSection secondSection = Sections[secondIndex];
var newSection = new IniSection(secondSection.SectionName);
foreach (var kvp in firstSection.Keys)
newSection.Keys.Add(kvp);
foreach (var kvp in secondSection.Keys)
{
int index = newSection.Keys.FindIndex(k => k.Key == kvp.Key);
if (index > -1)
newSection.Keys[index] = kvp;
else
newSection.Keys.Add(kvp);
}
Sections[secondIndex] = newSection;
}
/// <summary>
/// Returns a string value from the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="defaultValue">The value to return if the section or key wasn't found.</param>
/// <returns>The given key's value if the section and key was found. Otherwise the given defaultValue.</returns>
public string GetStringValue(string section, string key, string defaultValue)
{
IniSection iniSection = GetSection(section);
if (iniSection == null)
return defaultValue;
return iniSection.GetStringValue(key, defaultValue);
}
public string GetStringValue(string section, string key, string defaultValue, out bool success)
{
int sectionId = Sections.FindIndex(c => c.SectionName == section);
if (sectionId == -1)
{
success = false;
return defaultValue;
}
var kvp = Sections[sectionId].Keys.Find(k => k.Key == key);
if (kvp.Value == null)
{
success = false;
return defaultValue;
}
else
{
success = true;
return kvp.Value;
}
}
/// <summary>
/// Returns an integer value from the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="defaultValue">The value to return if the section or key wasn't found,
/// or converting the key's value to an integer failed.</param>
/// <returns>The given key's value if the section and key was found and
/// the value is a valid integer. Otherwise the given defaultValue.</returns>
public int GetIntValue(string section, string key, int defaultValue)
{
return Conversions.IntFromString(GetStringValue(section, key, null), defaultValue);
}
/// <summary>
/// Returns a double-precision floating point value from the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="defaultValue">The value to return if the section or key wasn't found,
/// or converting the key's value to a double failed.</param>
/// <returns>The given key's value if the section and key was found and
/// the value is a valid double. Otherwise the given defaultValue.</returns>
public double GetDoubleValue(string section, string key, double defaultValue)
{
return Conversions.DoubleFromString(GetStringValue(section, key, String.Empty), defaultValue);
}
/// <summary>
/// Returns a single-precision floating point value from the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="defaultValue">The value to return if the section or key wasn't found,
/// or converting the key's value to a float failed.</param>
/// <returns>The given key's value if the section and key was found and
/// the value is a valid float. Otherwise the given defaultValue.</returns>
public float GetSingleValue(string section, string key, float defaultValue)
{
return Conversions.FloatFromString(GetStringValue(section, key, String.Empty), defaultValue);
}
/// <summary>
/// Returns a boolean value from the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="defaultValue">The value to return if the section or key wasn't found,
/// or converting the key's value to a boolean failed.</param>
/// <returns>The given key's value if the section and key was found and
/// the value is a valid boolean. Otherwise the given defaultValue.</returns>
public bool GetBooleanValue(string section, string key, bool defaultValue)
{
return Conversions.BooleanFromString(GetStringValue(section, key, String.Empty), defaultValue);
}
/// <summary>
/// Parses and returns a path string from the INI file.
/// The path string has all of its directory separators ( / \ )
/// replaced with an environment-specific one.
/// </summary>
public string GetPathStringValue(string section, string key, string defaultValue)
{
IniSection iniSection = GetSection(section);
if (iniSection == null)
return defaultValue;
return iniSection.GetPathStringValue(key, defaultValue);
}
/// <summary>
/// Returns an INI section from the file, or null if the section doesn't exist.
/// </summary>
/// <param name="name">The name of the section.</param>
/// <returns>The section of the file; null if the section doesn't exist.</returns>
public IniSection GetSection(string name)
{
for (int i = _lastSectionIndex; i < Sections.Count; i++)
{
if (Sections[i].SectionName == name)
{
_lastSectionIndex = i;
return Sections[i];
}
}
int sectionId = Sections.FindIndex(c => c.SectionName == name);
if (sectionId == -1)
{
_lastSectionIndex = 0;
return null;
}
_lastSectionIndex = sectionId;
return Sections[sectionId];
}
/// <summary>
/// Sets the string value of a specific key of a specific section in the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="value">The value to set to the key.</param>
public void SetStringValue(string section, string key, string value)
{
var iniSection = Sections.Find(s => s.SectionName == section);
if (iniSection == null)
{
iniSection = new IniSection(section);
Sections.Add(iniSection);
}
iniSection.SetStringValue(key, value);
}
/// <summary>
/// Sets the integer value of a specific key of a specific section in the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="value">The value to set to the key.</param>
public void SetIntValue(string section, string key, int value)
{
var iniSection = Sections.Find(s => s.SectionName == section);
if (iniSection == null)
{
iniSection = new IniSection(section);
Sections.Add(iniSection);
}
iniSection.SetIntValue(key, value);
}
/// <summary>
/// Sets the double value of a specific key of a specific section in the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="value">The value to set to the key.</param>
public void SetDoubleValue(string section, string key, double value)
{
var iniSection = Sections.Find(s => s.SectionName == section);
if (iniSection == null)
{
iniSection = new IniSection(section);
Sections.Add(iniSection);
}
iniSection.SetDoubleValue(key, value);
}
public void SetSingleValue(string section, string key, float value)
{
SetSingleValue(section, key, value, 0);
}
public void SetSingleValue(string section, string key, double value, int decimals)
{
SetSingleValue(section, key, Convert.ToSingle(value), decimals);
}
/// <summary>
/// Sets the float value of a key in the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="value">The value to set to the key.</param>
/// <param name="decimals">Defines how many decimal places the stringified float should have.</param>
public void SetSingleValue(string section, string key, float value, int decimals)
{
string stringValue = value.ToString("N" + decimals, CultureInfo.GetCultureInfo("en-US").NumberFormat);
var iniSection = Sections.Find(s => s.SectionName == section);
if (iniSection == null)
{
iniSection = new IniSection(section);
Sections.Add(iniSection);
}
iniSection.SetStringValue(key, stringValue);
}
/// <summary>
/// Sets the boolean value of a key in the INI file.
/// </summary>
/// <param name="section">The name of the key's section.</param>
/// <param name="key">The name of the INI key.</param>
/// <param name="value">The value to set to the key.</param>
public void SetBooleanValue(string section, string key, bool value)
{
var iniSection = Sections.Find(s => s.SectionName == section);
if (iniSection == null)
{
iniSection = new IniSection(section);
Sections.Add(iniSection);
}
iniSection.SetBooleanValue(key, value);
}
/// <summary>
/// Gets the names of all INI keys in the specified INI section.
/// </summary>
public List<string> GetSectionKeys(string sectionName)
{
IniSection section = Sections.Find(c => c.SectionName == sectionName);
if (section == null)
return null;
List<string> returnValue = new List<string>();
section.Keys.ForEach(kvp => returnValue.Add(kvp.Key));
return returnValue;
}
/// <summary>
/// Gets the names of all sections in the INI file.
/// </summary>
public List<string> GetSections()
{
List<string> sectionList = new List<string>();
Sections.ForEach(section => sectionList.Add(section.SectionName));
return sectionList;
}
/// <summary>
/// Checks whether a section exists. Returns true if the section
/// exists, otherwise returns false.
/// </summary>
/// <param name="sectionName">The name of the INI section.</param>
/// <returns></returns>
public bool SectionExists(string sectionName)
{
return Sections.FindIndex(c => c.SectionName == sectionName) != -1;
}
/// <summary>
/// Checks whether a specific INI key exists in a specific INI section.
/// </summary>
/// <param name="sectionName">The name of the INI section.</param>
/// <param name="keyName">The name of the INI key.</param>
/// <returns>True if the key exists, otherwise false.</returns>
public bool KeyExists(string sectionName, string keyName)
{
IniSection section = GetSection(sectionName);
if (section == null)
return false;
return section.KeyExists(keyName);
}
}
}