-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIniFile.cs
2781 lines (2480 loc) · 110 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************
• File: IniFile.cs
• Description
THe IniFile is a class that represents a parser of ini files
using regular expressions.
The class implements methods for working with ini files:
- parsing INI files;
- getting sections, keys and values by sections and keys;
- setting values;
- automatically initializes properties.
To use the class, you must pass it a string or stream
containing the ini file data and some parsing settings.
• License
This software is distributed under the MIT License (MIT)
© 2024 Pavel Bashkardin.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated
documentation files (the “Software”), to deal in the
Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall
be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
***************************************************************/
#nullable disable
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
namespace System.Ini
{
/// <summary>
/// Attribute that associates a class or property with a specific section in the INI file.
/// Used by the <see cref="IniFile.ReadSettings"/> and <see cref="IniFile.WriteSettings"/> methods
/// to identify and process INI file sections.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
[Serializable]
public sealed class IniSectionAttribute : Attribute
{
private readonly string _sectionName = null;
/// <summary>
/// Initializes a new instance of the <see cref="IniSectionAttribute"/> class with a specified section name.
/// </summary>
/// <param name="sectionName">The name of the INI section.</param>
public IniSectionAttribute(string sectionName)
{
_sectionName = sectionName;
}
/// <summary>
/// Initializes a new instance of the <see cref="IniSectionAttribute"/> class with the default section name.
/// </summary>
public IniSectionAttribute()
{
}
/// <summary>
/// Gets the name of the INI section.
/// </summary>
public string Name
{
get => _sectionName;
}
/// <inheritdoc />
public override bool IsDefaultAttribute()
{
return string.IsNullOrEmpty(_sectionName);
}
/// <inheritdoc />
public override bool Match(object obj)
{
return obj is IniSectionAttribute attribute && attribute.Name.Equals(_sectionName);
}
/// <inheritdoc />
public override string ToString()
{
return _sectionName;
}
}
/// <summary>
/// Attribute that associates a property with a specific entry in the INI file.
/// Used by the <see cref="IniFile.ReadSettings"/> and <see cref="IniFile.WriteSettings"/> methods
/// to identify and process individual INI file entries.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
[Serializable]
public sealed class IniEntryAttribute : Attribute
{
private readonly string _entryName = null;
/// <summary>
/// Initializes a new instance of the <see cref="IniEntryAttribute"/> class with a specified entry name.
/// </summary>
/// <param name="entryName">The name of the INI entry.</param>
public IniEntryAttribute(string entryName)
{
_entryName = entryName;
}
/// <summary>
/// Initializes a new instance of the <see cref="IniEntryAttribute"/> class with the default entry name.
/// </summary>
public IniEntryAttribute()
{
}
/// <summary>
/// Gets the name of the INI entry.
/// </summary>
public string Name => _entryName;
/// <inheritdoc />
public override bool IsDefaultAttribute()
{
return string.IsNullOrEmpty(_entryName);
}
/// <inheritdoc />
public override bool Match(object obj)
{
return obj is IniEntryAttribute attribute && attribute.Name.Equals(_entryName);
}
/// <inheritdoc />
public override string ToString()
{
return _entryName;
}
}
/// <summary>
/// Represents a regular expression-based, collection-free INI file parser that preserves the original file formatting when editing entries.
/// </summary>
[Serializable]
public sealed class IniFile
{
// Private field for storing the content of the INI file.
private string _content;
// Cache of found matches, which improves performance.
[NonSerialized]
private List<Match> _matches;
// Regular expression used for parsing the INI file.
[NonSerialized]
private readonly Regex _regex;
// Indicates whether escape characters are allowed in the INI file.
[NonSerialized]
private readonly bool _allowEscapeChars = false;
// Indicates whether multi line values are allowed in the INI file.
[NonSerialized]
private readonly bool _allowMultiLine = false;
// String used to represent line breaks in the INI file.
[NonSerialized]
private readonly string _lineBreaker = Environment.NewLine;
// Contains culture-specific information for parsing.
[NonSerialized]
private readonly CultureInfo _culture = CultureInfo.InvariantCulture;
// Determines how string comparisons are performed in the INI file.
// Configured based on settings passed to the constructor.
[NonSerialized]
private readonly StringComparison _comparison = StringComparison.InvariantCultureIgnoreCase;
[NonSerialized]
private readonly HashSet<string> _trueValues;
[NonSerialized]
private readonly HashSet<string> _falseValues;
/// <summary>
/// Returns a string representing the contents of the INI file.
/// </summary>
public string Content
{
get
{
return _content ?? (_content = string.Empty);
}
set
{
_content = value ?? (_content = string.Empty);
_matches.Clear();
// Iterate over matches using the regex pattern and collect sections and entries names.
for (Match match = _regex.Match(_content); match.Success; match = match.NextMatch())
{
GroupCollection groups = match.Groups;
if (groups["section"].Success || groups["entry"].Success)
_matches.Add(match);
}
}
}
// Private constructor to prevent direct instantiation.
private IniFile()
{ }
// Constructor accepting ini content as a string and settings.
// Initializes the parser settings, setting the comparison rules,
// regular expression pattern, escape character allowance, and delimiter
// based on the provided settings.
private IniFile(string content,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
if (content == null) content = string.Empty;
_comparison = comparison;
_regex = new Regex(@"(?=\S)(?<text>(?<comment>(?<open>[#;]+)(?:[^\S\r\n]*)(?<value>.+))|" +
@"(?<section>(?<open>\[)(?:\s*)(?<value>[^\]]*\S+)(?:[^\S\r\n]*)(?<close>\]))|" +
@"(?<entry>(?<key>[^=\r\n\[\]]*\S)(?:[^\S\r\n]*)(?<delimiter>:|=)(?:[^\S\r\n]*)(?<value>[^#;\r\n]*))|" +
@"(?<undefined>.+))(?<=\S)|" +
@"(?<linebreaker>\r\n|\n)|" +
@"(?<whitespace>[^\S\r\n]+)",
GetRegexOptions(comparison, RegexOptions.Compiled));
_culture = GetCultureInfo(_comparison);
_allowEscapeChars = allowEscChars;
_lineBreaker = AutoDetectLineBreaker(content);
_matches = new List<Match>(16);
Content = content;
StringComparer comparer = GetComparer(comparison);
_trueValues = new HashSet<string>(comparer) { "true", "yes", "on", "enable", "1" };
_falseValues = new HashSet<string>(comparer) { "false", "no", "off", "disable", "0" };
}
/// <summary>
/// Create a new instance of <see cref="IniFile"/> with empty content.
/// </summary>
/// <param name="comparison">
/// Specifies the rules for string comparison.
/// </param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified settings.
/// </returns>
public static IniFile Create(StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
return new IniFile(string.Empty, comparison, allowEscChars);
}
/// <summary>
/// Loads an INI file using a <see cref="TextReader"/> and initializes an instance of <see cref="IniFile"/>.
/// </summary>
/// <param name="reader">
/// The <see cref="TextReader"/> containing the INI file data.
/// </param>
/// <param name="comparison">
/// Specifies the rules for string comparison.
/// </param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified data and settings.
/// </returns>
public static IniFile Load(TextReader reader,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
return new IniFile(reader.ReadToEnd(), comparison, allowEscChars);
}
/// <summary>
/// Loads an INI file from a <see cref="Stream"/> using the specified encoding and initializes an instance of <see cref="IniFile"/>.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> containing the INI file data.
/// </param>
/// <param name="encoding">
/// The <see cref="Encoding"/> used to read the stream.
/// </param>
/// <param name="comparison">
/// Specifies the rules for string comparison.
/// </param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified data and settings.
/// </returns>
public static IniFile Load(Stream stream, Encoding encoding = null,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
using (StreamReader reader = new StreamReader(stream ?? throw new ArgumentNullException(nameof(stream)), encoding ?? Encoding.UTF8))
return new IniFile(reader.ReadToEnd(), comparison, allowEscChars);
}
/// <summary>
/// Loads an INI file from a file specified by its path using the specified encoding and initializes an instance of <see cref="IniFile"/>.
/// </summary>
/// <param name="fileName">
/// The path to the file containing the INI data.
/// </param>
/// <param name="encoding">
/// The <see cref="Encoding"/> used to read the file.
/// </param>
/// <param name="comparison">
/// Specifies the rules for string comparison.
/// </param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified data and settings.
/// </returns>
public static IniFile Load(string fileName,
Encoding encoding,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
string filePath = GetFullPath(fileName, true);
return new IniFile(File.ReadAllText(filePath, encoding ?? AutoDetectEncoding(filePath, Encoding.UTF8)),
comparison, allowEscChars);
}
/// <summary>
/// Loads an INI file from a file specified by its path using the specified encoding and initializes an instance of <see cref="IniFile"/>.
/// </summary>
/// <param name="fileName">
/// The path to the file containing the INI data.
/// </param>
/// <param name="comparison">
/// Specifies the rules for string comparison.
/// </param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified data and settings.
/// </returns>
public static IniFile Load(string fileName,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
string filePath = GetFullPath(fileName, true);
return new IniFile(File.ReadAllText(filePath, AutoDetectEncoding(filePath, Encoding.UTF8)),
comparison, allowEscChars);
}
/// <summary>
/// Loads an INI file using a <see cref="TextReader"/> or create it with empty content
/// and initializes an instance of <see cref="IniFile"/>.
/// </summary>
/// <param name="fileName">
/// The path to the file containing the INI data.
/// </param>
/// <param name="encoding">
/// The <see cref="Encoding"/> used to read the file.
/// </param>
/// <param name="comparison">
/// Specifies the rules for string comparison.</param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified settings.
/// </returns>
public static IniFile LoadOrCreate(string fileName, Encoding encoding,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
string filePath = GetFullPath(fileName);
return new IniFile(
File.Exists(filePath)
? File.ReadAllText(filePath, encoding ?? AutoDetectEncoding(filePath, Encoding.UTF8))
: string.Empty,
comparison, allowEscChars);
}
/// <summary>
/// Loads an INI file using a <see cref="TextReader"/> or create it with empty content
/// and initializes an instance of <see cref="IniFile"/>.
/// </summary>
/// <param name="fileName">
/// The path to the file containing the INI data.
/// </param>
/// <param name="comparison">
/// Specifies the rules for string comparison.</param>
/// <param name="allowEscChars">
/// Indicates whether escape characters are allowed in the INI file.
/// </param>
/// <returns>
/// An instance of <see cref="IniFile"/> initialized with the specified settings.
/// </returns>
public static IniFile LoadOrCreate(string fileName,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase,
bool allowEscChars = false)
{
string filePath = GetFullPath(fileName);
return new IniFile(
File.Exists(filePath)
? File.ReadAllText(filePath, AutoDetectEncoding(filePath, Encoding.UTF8))
: string.Empty,
comparison, allowEscChars);
}
/// <summary>
/// Saves the INI file content to a <see cref="TextWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="TextWriter"/> where the INI file data will be written.</param>
public void Save(TextWriter writer)
{
writer.Write(Content);
}
/// <summary>
/// Saves the INI file content to a <see cref="Stream"/> using the specified encoding.
/// </summary>
/// <param name="stream">
/// The <see cref="Stream"/> where the INI file data will be written.
/// </param>
/// <param name="encoding">
/// The <see cref="Encoding"/> used to write the data to the stream.
/// </param>
public void Save(Stream stream, Encoding encoding = null)
{
using (StreamWriter writer = new StreamWriter(stream, encoding ?? Encoding.UTF8))
{
writer.Write(Content);
}
}
/// <summary>
/// Saves the INI file content to a file specified by its path using the specified encoding.
/// </summary>
/// <param name="fileName">
/// The path to the file where the INI data will be saved.
/// </param>
/// <param name="encoding">
/// The <see cref="Encoding"/> used to write the file.
/// </param>
public void Save(string fileName, Encoding encoding = null)
{
string fullPath = GetFullPath(fileName);
File.WriteAllText(fullPath, Content, encoding ?? Encoding.UTF8);
}
// Method to retrieve all sections in the INI file.
private IEnumerable<string> GetSections()
{
HashSet<string> sections = new HashSet<string>(GetComparer(_comparison));
// Iterate over matches using the regex pattern and collect section names.
//foreach (Match match in _matches)
for (int i = 0; i < _matches.Count; i++)
{
Match match = _matches[i];
if (match.Groups["section"].Success)
{
// Convert to lowercase if ignore case mode is enabled.
string section = MayBeToLower(match.Groups["value"].Value, _comparison);
sections.Add(section);
}
}
return sections;
}
// Method to retrieve all keys in a specific section.
private IEnumerable<string> GetKeys(string section)
{
HashSet<string> keys = new HashSet<string>(GetComparer(_comparison));
bool emptySection = string.IsNullOrEmpty(section);
bool inSection = emptySection;
// Iterate through the content to find keys within the specified section.
for (int i = 0; i < _matches.Count; i++)
{
Match match = _matches[i];
// If the section name is not specified, then the parameters without a section,
// which are located above the first section, are used.
if (match.Groups["section"].Success)
{
inSection = match.Groups["value"].Value.Equals(section, _comparison);
if (emptySection) break;
continue;
}
if (inSection && match.Groups["entry"].Success)
{
string key = MayBeToLower(match.Groups["key"].Value, _comparison);
keys.Add(key);
}
}
return keys;
}
// Method to get a value from a specific section and key, with an optional default value.
private string GetValue(string section, string key, string defaultValue = null)
{
string value = defaultValue;
bool emptySection = string.IsNullOrEmpty(section);
bool inSection = emptySection;
// Search for the section and key, and return the corresponding value.
for (int i = 0; i < _matches.Count; i++)
{
Match match = _matches[i];
if (match.Groups["section"].Success)
{
inSection = match.Groups["value"].Value.Equals(section, _comparison);
if (emptySection) break;
continue;
}
if (inSection && match.Groups["entry"].Success)
{
if (!match.Groups["key"].Value.Equals(key, _comparison))
continue;
value = match.Groups["value"].Value;
if (_allowEscapeChars) value = UnEscape(value);
return value;
}
}
return value;
}
// Method to get all values in a specific section.
private IEnumerable<string> GetValues(string section)
{
List<string> values = new List<string>();
bool emptySection = string.IsNullOrEmpty(section);
bool inSection = emptySection;
// Collect all values within the specified section.
for (int i = 0; i < _matches.Count; i++)
{
Match match = _matches[i];
if (match.Groups["section"].Success)
{
inSection = match.Groups["value"].Value.Equals(section, _comparison);
if (emptySection) break;
continue;
}
if (inSection && match.Groups["entry"].Success)
{
string value = match.Groups["value"].Value;
if (_allowEscapeChars) value = UnEscape(value);
values.Add(value);
}
}
return values;
}
// Method to get all values associated with a specific key in a section.
private IEnumerable<string> GetValues(string section, string key)
{
// If the key is empty, return all the values in the section.
if (string.IsNullOrEmpty(key)) return GetValues(section);
List<string> values = new List<string>();
bool emptySection = string.IsNullOrEmpty(section);
bool inSection = emptySection;
// Collect all values corresponding to the key in the section.
for (int i = 0; i < _matches.Count; i++)
{
Match match = _matches[i];
if (match.Groups["section"].Success)
{
inSection = match.Groups["value"].Value.Equals(section, _comparison);
if (emptySection) break;
continue;
}
if (inSection && match.Groups["entry"].Success)
{
if (!match.Groups["key"].Value.Equals(key, _comparison))
continue;
string value = match.Groups["value"].Value;
if (_allowEscapeChars) value = UnEscape(value);
values.Add(value);
}
}
return values;
}
// Sets a single value for a specified key in a given section.
private void SetValue(string section, string key, string value)
{
bool emptySection = string.IsNullOrEmpty(section);
bool expectedValue = !string.IsNullOrEmpty(value); // Indicates that value is not set.
bool inSection = emptySection;
Match lastMatch = null; // Keep track of the last match for future reference.
StringBuilder sb = new StringBuilder(_content);
// Escape the value if necessary.
if (_allowEscapeChars && expectedValue) value = ToEscape(value);
// Iterate over the content to find the section and key, and set the value.
for (int i = 0; i < _matches.Count; i++)
{
Match match = _matches[i];
if (match.Groups["section"].Success)
{
inSection = match.Groups["value"].Value.Equals(section, _comparison);
if (emptySection) break; // If no section is specified, break out of the loop.
continue;
}
// If inside the correct section and the match is an entry.
if (inSection && match.Groups["entry"].Success)
{
lastMatch = match;
// Continue if the key doesn't match.
if (!match.Groups["key"].Value.Equals(key, _comparison))
continue;
// Remove the existing value associated with the key
// and insert the new value in its place if it is not empty.
Group group = match.Groups["value"];
int index = group.Index;
int length = group.Length;
if (expectedValue)
{
// Remove the old value.
sb.Remove(index, length);
// Insert the new value in its place.
sb.Insert(index, value);
}
else
{
// Remove all entry.
sb.Remove(match.Index, match.Length);
}
// Indicate the value has been set.
expectedValue = false;
break;
}
}
// If the key doesn't exist, append the new value at the correct position.
if (expectedValue)
{
int index = 0;
// If a match was found previously, append after the last match.
if (lastMatch != null)
{
index = lastMatch.Index + lastMatch.Length;
}
// If no match was found, append a new section and then insert the key-value pair
else if (!emptySection)
{
// Add the section header.
sb.Append(_lineBreaker);
sb.Append($"[{section}]{_lineBreaker}");
index = sb.Length; // Set the index to the end of the StringBuilder.
}
// Insert the new key-value pair into the content.
string line = $"{key}={value}";
InsertLine(sb, ref index, _lineBreaker, line);
}
Content = sb.ToString();
}
// Sets multiple values for a specific key in a section.
private void SetValues(string section, string key, params string[] values)
{
int valueIndex = 0; // Track the index of the current value being processed.
bool emptySection = string.IsNullOrEmpty(section);
bool inSection = emptySection;
Match lastMatch = null; // Keep track of the last regex match found.
StringBuilder sb = new StringBuilder(_content); // Create a StringBuilder to modify the ini content.
int offset = 0; // Offset to account for changes in length during replacements.
// Iterate over the ini content and process each match for section and entry
for (int i = 0; valueIndex < values.Length && i < _matches.Count; i++)
{
Match match = _matches[i];
if (match.Groups["section"].Success) // Check if the current match is a section.
{
// Set the inSection flag based on whether the section matches the target section.
inSection = match.Groups["value"].Value.Equals(section, _comparison);
if (emptySection) break; // If there is no section, break out of the loop.
continue;
}
// Check if inside the correct section and the current match is an entry.
if (inSection && match.Groups["entry"].Success)
{
lastMatch = match;
// Check if the key matches.
if (!match.Groups["key"].Value.Equals(key, _comparison))
continue;
// Get the group representing the value.
Group group = match.Groups["value"];
// Get the new value to insert.
string newValue = values[valueIndex++] ?? string.Empty;
string oldValue = group.Value;
// Calculate the index considering previous modifications.
int index = group.Index + offset;
int length = group.Length;
// Remove the old value and insert the new one.
sb = sb.Remove(index, length);
if (_allowEscapeChars) newValue = ToEscape(newValue);
sb = sb.Insert(index, newValue);
// Update the offset for future replacements.
offset += newValue.Length - oldValue.Length;
}
}
// If there are still values left to be processed, append them at the end of the section.
if (valueIndex < values.Length)
{
int index = 0;
// If a previous match was found, insert after the last entry.
if (lastMatch != null)
{
index = lastMatch.Index + lastMatch.Length;
}
// If no match was found, append a new section header if necessary.
else if (!emptySection)
{
sb.Append(_lineBreaker);
sb.Append($"[{section}]{_lineBreaker}");
index = sb.Length;
}
// Insert the remaining values as new entries in the section.
while (valueIndex < values.Length)
{
// Obtaining the next value.
string value = values[valueIndex++];
if (_allowEscapeChars) value = ToEscape(value); // Escape characters if allowed.
// Insert the new key-value pair into the content.
string line = $"{key}={value}";
InsertLine(sb, ref index, _lineBreaker, line);
}
}
// Update the content with the modified StringBuilder content
Content = sb.ToString();
}
// Returns a CultureInfo object that defines the string comparison rules for the specified StringComparison.
private static CultureInfo GetCultureInfo(StringComparison comparison)
{
return comparison < StringComparison.InvariantCulture
? CultureInfo.CurrentCulture
: CultureInfo.InvariantCulture;
}
// Sets or clears the RegexOptions flags based on the specified StringComparison, returning the modified value.
private static RegexOptions GetRegexOptions(StringComparison comparison, RegexOptions options = RegexOptions.None)
{
switch (comparison)
{
case StringComparison.CurrentCulture:
options &= ~RegexOptions.CultureInvariant;
break;
case StringComparison.CurrentCultureIgnoreCase:
options &= ~RegexOptions.CultureInvariant;
options |= RegexOptions.IgnoreCase;
break;
case StringComparison.InvariantCulture:
options |= RegexOptions.CultureInvariant;
break;
case StringComparison.InvariantCultureIgnoreCase:
options |= RegexOptions.IgnoreCase | RegexOptions.CultureInvariant;
break;
case StringComparison.OrdinalIgnoreCase:
options |= RegexOptions.IgnoreCase;
break;
}
return options;
}
// Returns the StringComparer based on the specified StringComparison.
private static StringComparer GetComparer(StringComparison comparison)
{
switch (comparison)
{
case StringComparison.CurrentCulture:
return StringComparer.CurrentCulture;
case StringComparison.CurrentCultureIgnoreCase:
return StringComparer.CurrentCultureIgnoreCase;
case StringComparison.InvariantCulture:
return StringComparer.InvariantCulture;
case StringComparison.InvariantCultureIgnoreCase:
return StringComparer.InvariantCultureIgnoreCase;
case StringComparison.Ordinal:
return StringComparer.Ordinal;
case StringComparison.OrdinalIgnoreCase:
return StringComparer.OrdinalIgnoreCase;
default:
return StringComparer.InvariantCultureIgnoreCase;
}
}
// Escape characters in the input string with backslashes.
private static string ToEscape(string text)
{
int pos = 0;
int inputLength = text.Length;
if (inputLength == 0) return text;
StringBuilder sb = new StringBuilder(inputLength * 2);
do
{
char c = text[pos++];
switch (c)
{
case '\\':
sb.Append(@"\\");
break;
case '\0':
sb.Append(@"\0");
break;
case '\a':
sb.Append(@"\a");
break;
case '\b':
sb.Append(@"\b");
break;
case '\n':
sb.Append(@"\n");
break;
case '\r':
sb.Append(@"\r");
break;
case '\f':
sb.Append(@"\f");
break;
case '\t':
sb.Append(@"\t");
break;
case '\v':
sb.Append(@"\v");
break;
default:
sb.Append(c);
break;
}
} while (pos < inputLength);
return sb.ToString();
}
// Converts hex number to unicode character.
private static char UnHex(string hex)
{
int c = 0;
for (int i = 0; i < hex.Length; i++)
{
int r = hex[i]; // Obtain next digit.
if (r > 0x2F && r < 0x3A) r -= 0x30;
else if (r > 0x40 && r < 0x47) r -= 0x37;
else if (r > 0x60 && r < 0x67) r -= 0x57;
else return '?';
c = (c << 4) + r; // Insert next digit.
}
return (char)c;
}
// Converts any escaped characters in the input string.
private static string UnEscape(string text)
{
int pos = -1;
int inputLength = text.Length;
if (inputLength == 0) return text;
// Find the first occurrence of backslash or return the original text.
for (int i = 0; i < inputLength; ++i)
{
if (text[i] == '\\')
{
pos = i;
break;
}
}
if (pos < 0) return text; // Backslash not found.
// If backslash is found.
StringBuilder sb = new StringBuilder(text.Substring(0, pos));
do
{
char c = text[pos++];
if (c == '\\')
{
c = pos < inputLength ? text[pos] : '\\';
switch (c)
{
case '\\':
c = '\\';
break;
case '0':
c = '\0';
break;
case 'a':
c = '\a';
break;
case 'b':
c = '\b';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 'f':
c = '\f';
break;
case 't':
c = '\t';
break;
case 'v':
c = '\v';
break;
case 'u' when pos < inputLength - 3: