Esempio n. 1
0
        //private string OpenFileDialog()
        //{
        //    return _openFileDialog.ShowDialog() ?? false ? _openFileDialog.FileName : "";
        //}

        private bool LoadINI(string path, out INI file)
        {
            if (!File.Exists(path))
            {
                file = null;
                return false;
            }

            Regex iniHeader = new Regex(@"^\[[^\]\r\n]+]");
            Regex iniKeyValue = new Regex(@"^([^=;\r\n]+)=([^;\r\n]*)");

            var lines = File.ReadAllLines(path);
            file = new INI();

            var duplicateKeys = new List<Tuple<string, string, string, string>>(); //block, key, old value, new value

            Dictionary<string, string> currentBlock = null;
            foreach (var line in lines)
            {
                try
                {
                    if (iniHeader.IsMatch(line))
                        file.Add(line.Trim(new char[] { ' ', ']', '[', '\t' }), currentBlock = new INIBlock());

                    if (iniKeyValue.IsMatch(line))
                    {
                        if (currentBlock == null)
                            file.Add("", currentBlock = new INIBlock());

                        var match = iniKeyValue.Match(line);
                        var key = match.Groups[1].Value.Trim();
                        var value = match.Groups[2].Value.Trim();

                        if (currentBlock.ContainsKey(key))
                        {
                            var currentBlockName = file.FirstOrDefault(kv => kv.Value == currentBlock).Key;
                            duplicateKeys.Add(Tuple.Create(currentBlockName, key, currentBlock[key], value));

                            currentBlock[key] = value;
                        }
                        else
                        {
                            currentBlock.Add(key, value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("This INI could not be parsed. The line being parsed was:\n" + line +
                        "\n\nDetailed exception information below:\n" + ex.InnerException
                        , "Exception Alert", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    file = null;
                    return false;
                }
            }
            if (duplicateKeys.Count > 0)
                MessageBox.Show(string.Format("{0} values were overwritten by same keys in the same section. Only the last set value for the key will be used.\n[Section] Key = Early Value -> Later Value\n{1}"
                    , duplicateKeys.Count, String.Join("\n", duplicateKeys.Select(dup => string.Format("[{0}] {1} = {2} -> {3}", dup.Item1, dup.Item2, dup.Item3, dup.Item4))))
                    , "Duplicate Key-Values Overwritten", MessageBoxButton.OK, MessageBoxImage.Information);
            return true;

        }