/// <summary> /// Converts the collection to an INI-formatted formatted string with the specified options. /// </summary> /// <param name="format"></param> /// <returns>An INI-formatted formatted string that contains the keys and values in the collection.</returns> public string ToString(IniConfigurationFormat format) { StringBuilder sb = new StringBuilder(); WriteSection(sb, this.DefaultSection, format); foreach (string section in this) { WriteSection(sb, (IniConfigurationSection)BaseGet(section), format); } return(sb.ToString()); }
/// <summary> /// Converts the collection to an INI-formatted formatted string with the specified options. /// </summary> /// <param name="format"></param> /// <param name="formatProvider"></param> /// <returns></returns> public string ToString(string format, IFormatProvider formatProvider) { IniConfigurationFormat f = 0; if (format != null) { if (format.IndexOfAny(new[] { 'q', 'Q' }) >= 0) { f |= IniConfigurationFormat.ForceQuote; } if (format.IndexOfAny(new[] { 's', 'S' }) >= 0) { f |= IniConfigurationFormat.SortKey; } if (format.IndexOfAny(new[] { 'c', 'C' }) >= 0) { f |= IniConfigurationFormat.PreserveComment; } } return(ToString(f)); }
private static void WriteSection(StringBuilder sb, IniConfigurationSection section, IniConfigurationFormat format) { IniConfigurationSection n = new IniConfigurationSection(section); if (section.Name != String.Empty && sb.Length > 0) { sb.AppendLine(); } if (format.HasFlag(IniConfigurationFormat.PreserveComment)) { WriteComment(sb, section.GetComment()); } if (section.Name != String.Empty) { sb.Append('['); sb.Append(section.Name); sb.AppendLine("]"); } string[] keys = new string[section.AllKeys.Length]; Array.Copy(section.AllKeys, keys, keys.Length); if (format.HasFlag(IniConfigurationFormat.SortKey)) { Array.Sort(keys); } foreach (string key in keys) { if (format.HasFlag(IniConfigurationFormat.PreserveComment)) { WriteComment(sb, n.GetComment(key)); n.RemoveComment(key); } foreach (string value in section.GetValues(key)) { var hasQuote = format.HasFlag(IniConfigurationFormat.ForceQuote) || value.IndexOf('"') >= 0; var quotedValue = hasQuote ? value.Replace("\"", "\\\"") : value; var isNewLine = false; sb.Append(key); sb.Append('='); if (hasQuote) { sb.Append('"'); } foreach (string line in quotedValue.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)) { if (isNewLine) { sb.Append('\\'); sb.AppendLine(); } else { isNewLine = true; } sb.Append(line); } if (hasQuote) { sb.Append('"'); } sb.AppendLine(); } } }