IniParserConfiguration code example

Example: IniParserConfiguration

public static IniData ParseFiles(string defaultConfig, string globalConfigFilename)
        {
            var utf8 = new UTF8Encoding(false);
            var parserConfig = new IniParserConfiguration {
                // ThrowExceptionsOnError = false,
                CommentString = "#",
                SkipInvalidLines = true
            };

            var parser = new IniDataParser(parserConfig);
            IniData result = parser.Parse(DefaultLfMergeSettings.DefaultIniText);

            string globalIni = File.Exists(globalConfigFilename) ? File.ReadAllText(globalConfigFilename, utf8) : "";
            if (String.IsNullOrEmpty(globalIni))
            {
                // TODO: Make all these Console.WriteLine calls into proper logging calls
                Console.WriteLine("Warning: no global configuration found. Will use default settings.");
            }
            IniData globalConfig;
            try
            {
                globalConfig = parser.Parse(globalIni);
            }
            catch (ParsingException e)
            {
                Console.WriteLine("Warning: Error parsing global configuration file. Will use default settings.");
                Console.WriteLine("Error follows: {0}", e.ToString());
                globalConfig = null; // Merging null is perfectly acceptable to IniParser
            }
            result.Merge(globalConfig);

            foreach (KeyData item in result.Global)
            {
                // Special-case. Could be replaced with a more general regex if we end up using more variables, but YAGNI.
                if (item.Value.Contains("${HOME}"))
                {
                    item.Value = item.Value.Replace("${HOME}", Environment.GetEnvironmentVariable("HOME"));
                }
            }

            return result;
        }

Tags:

Php Example