-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIniFileProvider.cs
427 lines (394 loc) · 13.5 KB
/
IniFileProvider.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
/* ***********************************************
* Copyright (c) 2009-2010 luoshasha. All rights reserved";
* CLR version: 4.0.30319.296"
* File name: IniFileProvider.cs"
* Date: 12/5/2012 11:44:15 AM
* Author : luoshasha(sand)
* Email : [email protected]
* Description:
* History: created by luoshasha(sand) 12/5/2012 11:44:15 AM
* ***********************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace SandLib.Util
{
/// <summary>
/// a ini file provider can read and write ini files,
/// support empty lines and comment.
/// </summary>
public class IniFileProvider
{
private readonly Regex _section_rex = new Regex(@"(?<=\[)(?<SectionName>[^\]]+)(?=\])");
private readonly Regex _kv_rex = new Regex(@"(?<Key>[^=]+)=(?<Value>.+)");
private readonly Regex _comment_rex = new Regex(@"^[;#]");
private readonly Regex _empty_rex = new Regex(@"\s+");
private List<Entry> _file_global_entries = new List<Entry>();
private Dictionary<string, SectionEntry> _sections = new Dictionary<string, SectionEntry>();
private string _filename;
public IniFileProvider() : this(null) { }
public IniFileProvider(string filename)
{
if (!string.IsNullOrEmpty(filename))
Load(filename);
}
/// <summary>
/// gets current loaded ini file
/// </summary>
public string FileName
{
get { return _filename; }
}
/// <summary>
/// Get a specific value from the .ini file
/// </summary>
/// <param name="sectionName"></param>
/// <param name="key"></param>
/// <returns>The value of the given key in the given section, or NULL if not found</returns>
public string GetValue(string sectionName, string key)
{
sectionName = sectionName.ToLower();
key = key.ToLower();
SectionEntry se = null;
_sections.TryGetValue(sectionName, out se);
if (se != null)
return se.GetKVEntry(key).Value;
return null;
}
/// <summary>
/// Set a specific value in a section
/// </summary>
/// <param name="sectionName"></param>
/// <param name="key"></param>
/// <param name="value"></param>
public void SetValue(string sectionName, string key, string value)
{
sectionName = sectionName.ToLower();
key = key.ToLower();
SectionEntry se = null;
if (!_sections.TryGetValue(sectionName, out se))
{
se = new SectionEntry(sectionName);
_sections[sectionName] = se;
_file_global_entries.Add(se);
}
se.SetKeyValue(key, value);
}
/// <summary>
/// Set an entire sections values
/// </summary>
/// <param name="sectionName"></param>
/// <param name="sectionValues"></param>
public void SetSection(string sectionName, IDictionary<string, string> sectionValues)
{
sectionName = sectionName.ToLower();
SectionEntry se = null;
if (!_sections.TryGetValue(sectionName, out se))
{
se = new SectionEntry(sectionName);
_sections[sectionName] = se;
_file_global_entries.Add(se);
}
foreach (var kv in sectionValues)
{
string key = kv.Key.ToLower();
se.SetKeyValue(key, kv.Value);
}
}
/// <summary>
/// load an ini file by default encoding
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool Load(string filename)
{
return this.Load(filename, Encoding.Default);
}
/// <summary>
/// Load an .INI File
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool Load(string filename, Encoding encoding)
{
_filename = filename;
if (!File.Exists(filename))
return false;
try
{
string[] content = File.ReadAllLines(filename, encoding);
SectionEntry current_se = null;
foreach (var line in content)
{
//match section
Match m = _section_rex.Match(line);
if (m.Success)
{
current_se = new SectionEntry(m.Groups[1].Value.Trim().ToLower());
_file_global_entries.Add(current_se);
_sections[current_se.SectionName] = current_se;
continue;
}
//match empty lines
m = _empty_rex.Match(line);
if (m.Success)
{
Entry entry = new TextLineEntry(EntryType.Empty, line);
if (current_se == null)
_file_global_entries.Add(entry);//global entry
else
current_se.AddEntry(entry);//sub entry
continue;
}
//match comment
m = _comment_rex.Match(line);
if (m.Success)
{
Entry entry = new TextLineEntry(EntryType.Comment, line);
if (current_se == null)
_file_global_entries.Add(entry);//global entry
else
current_se.AddEntry(entry);//sub entry
continue;
}
m = _kv_rex.Match(line);
if (m.Success)
{
string key = m.Groups[1].Value.Trim().ToLower();
string value = m.Groups[2].Value.Trim();
//如果字符串值带有前后引号,则删除前后引号
if (value.StartsWith("\"") && value.EndsWith("\""))
value = value.Substring(1, value.Length - 2);
//must has a section
if (current_se != null)
{
current_se.SetKeyValue(key, value);
}
else
{
//or we consider it as a unknown line
Entry unknown = new TextLineEntry(EntryType.Unknown, line);
_file_global_entries.Add(unknown);
}
continue;
}
//at this point all matches are failed
//create a unknown entry
Entry unknown_entry = new TextLineEntry(EntryType.Unknown, line);
if (current_se != null)
current_se.AddEntry(unknown_entry);
else
_file_global_entries.Add(unknown_entry);
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// save back to loaded file
/// </summary>
/// <returns></returns>
public bool Save()
{
return Save(_filename);
}
/// <summary>
/// save to an ini file using a default ini
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool Save(string filename)
{
return Save(filename, Encoding.Default);
}
/// <summary>
/// Save the content of this class to an INI File
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool Save(string filename, Encoding encoding)
{
var sb = new StringBuilder();
int entry_count = _file_global_entries.Count;
for (int i = 0; i < entry_count; ++i)
{
sb.AppendLine(_file_global_entries[i].GetEntryLines());
}
try
{
File.WriteAllText(filename, sb.ToString(), encoding);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Get a specific value
/// </summary>
/// <param name="key">format:sectionMane:keyName</param>
/// <returns></returns>
private string this[string key]
{
get
{
string text1 = null;
try
{
int separatorIndex = key.IndexOf(':');
string sectionName = key.Substring(0, separatorIndex).Trim().ToLower();
string keyName = key.Substring(separatorIndex + 1).Trim().ToLower();
text1 = this.GetValue(sectionName, keyName);
}
catch
{
}
return text1;
}
}
/// <summary>
/// gets all section names
/// </summary>
public IEnumerable<string> SectionNames
{
get { return _sections.Keys; }
}
/// <summary>
/// gets number of sections
/// </summary>
public int SectionCount
{
get { return _sections.Count; }
}
/// <summary>
/// gets all file entry count
/// </summary>
public int EntryCount
{
get { return _file_global_entries.Count; }
}
/// <summary>
/// gets entry by index
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public Entry GetEntry(int index)
{
return _file_global_entries[index];
}
public string GetString(string key, string defaultValue)
{
string retValue = this[key];
if (retValue != null)
return retValue;
else
return defaultValue;
}
public object Get(string key, Type type)
{
if (key == null || type == null)
{
throw new ArgumentNullException();
}
if (type == typeof(string))
{
return this[key];
}
if (type == typeof(int))
{
return this.GetInt(key, 0);
}
if (type == typeof(float))
{
return this.GetSingle(key, 0.0f);
}
if (type == typeof(double))
{
return this.GetDouble(key, 0.0);
}
if (type == typeof(bool))
{
return this.GetBoolean(key, false);
}
if (type == typeof(DateTime))
{
return this.GetDateTime(key, DateTime.MinValue);
}
if (type == typeof(TimeSpan))
{
return this.GetTimeSpan(key, TimeSpan.MinValue);
}
if (type.IsEnum)
{
try
{
return Enum.Parse(type, this[key]);
}
catch { }
}
return null;
}
public int GetInt(string key, int defaultValue)
{
try
{
return int.Parse(this[key]);
}
catch { }
return defaultValue;
}
public Single GetSingle(string key, float defaultValue)
{
try
{
return Single.Parse(this[key]);
}
catch { }
return defaultValue;
}
public double GetDouble(string key, double defaultValue)
{
try
{
return double.Parse(this[key]);
}
catch { }
return defaultValue;
}
public bool GetBoolean(string key, bool defaultValue)
{
try
{
return bool.Parse(this[key]);
}
catch { }
return defaultValue;
}
public DateTime GetDateTime(string key, DateTime defaultValue)
{
try
{
return DateTime.Parse(this[key].Trim());
}
catch
{ }
return defaultValue;
}
public TimeSpan GetTimeSpan(string key, TimeSpan defaultValue)
{
try
{
return TimeSpan.Parse(this[key]);
}
catch
{ }
return defaultValue;
}
}
}