2 using System.Collections.Generic;
4 using System.Text.RegularExpressions;
10 public string[] keys {
get {
return _dict.Keys.ToArray(); } }
11 public string[] values {
get {
return _dict.Values.ToArray(); } }
13 public int count {
get {
return _dict.Count; } }
15 public string this[
string key] {
16 get {
return _dict[key]; }
18 _dict[key.Trim()] = value
21 .Replace(
"\\t",
"\t");
25 readonly Dictionary<string, string> _dict;
31 properties = convertLineEndings(properties);
32 _dict =
new Dictionary<string, string>();
33 var lines = getLinesWithProperties(properties);
34 addProperties(mergeMultilineValues(lines));
35 replacePlaceholders();
38 public bool HasKey(
string key) {
39 return _dict.ContainsKey(key);
42 static string convertLineEndings(
string str) {
43 return str.Replace(
"\r\n",
"\n").Replace(
"\r",
"\n");
46 static string[] getLinesWithProperties(
string properties) {
47 var delimiter =
new[] {
'\n' };
49 .Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
50 .Select(line => line.TrimStart(
' '))
51 .Where(line => !line.StartsWith(
"#", StringComparison.Ordinal))
55 static string[] mergeMultilineValues(
string[] lines) {
56 var currentProperty =
string.Empty;
57 return lines.Aggregate(
new List<string>(), (acc, line) => {
58 currentProperty += line;
59 if(currentProperty.EndsWith(
"\\", StringComparison.Ordinal)) {
60 currentProperty = currentProperty.Substring(
61 0, currentProperty.Length - 1
64 acc.Add(currentProperty);
65 currentProperty =
string.Empty;
72 void addProperties(
string[] lines) {
73 var keyValueDelimiter =
new[] {
'=' };
74 var properties = lines.Select(
75 line => line.Split(keyValueDelimiter, 2)
77 foreach(var property
in properties) {
78 this[
property[0]] =
property[1];
82 void replacePlaceholders() {
83 const string placeholderPattern =
@"(?:(?<=\${).+?(?=}))";
84 foreach(var key
in _dict.Keys.ToArray()) {
85 var matches = Regex.Matches(_dict[key], placeholderPattern);
86 foreach(Match match
in matches) {
87 _dict[key] = _dict[key].Replace(
88 "${" + match.Value +
"}", _dict[match.Value]
94 public override string ToString() {
95 return _dict.Aggregate(
string.Empty, (properties, kv) => {
96 var content = kv.Value
98 .Replace(
"\t",
"\\t");
100 return properties + kv.Key +
" = " + content +
"\n";