Exemple #1
0
        /// <summary>
        /// Parse the given text into an <see cref="IniDocument"/>.
        /// </summary>
        /// <param name="text">The text to parse.</param>
        public IniDocumentBuilder Parse(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return(this);
            }

            var comment    = Comment.Builder().Build();
            var sName      = string.Empty;
            var sIsEnabled = true;

            foreach (var line in text.SplitToLines().Select(l => l.Trim()).Where(l => l != ""))
            {
                if (line.IsHeader())
                {
                    _header = Comment.Builder(_header).AsType(CommentType.Header).AppendLine(line).Build();
                    continue;
                }

                if (line.IsFooter())
                {
                    _footer = Comment.Builder(_footer).AsType(CommentType.Footer).AppendLine(line).Build();
                    continue;
                }

                if (line.CommentIsValidAndUpdated(ref comment))
                {
                    continue;
                }

                if (line.SectionIsValidAndUpdated(ref sName, ref sIsEnabled))
                {
                    AppendSection(Section
                                  .Builder()
                                  .IsEnable(sIsEnabled)
                                  .WithName(sName)
                                  .WithComment(comment)
                                  .Build());

                    comment = Comment.Builder().Build();
                    continue;
                }

                if (line.PropertyIsValidAndUpdated(out var key, out var value, out var isEnabled))
                {
                    AppendProperty(sName, Property
                                   .Builder()
                                   .WithKey(key)
                                   .WithValue(value)
                                   .WithComment(comment)
                                   .IsEnable(isEnabled)
                                   .Build());

                    comment = Comment.Builder().Build();
                }
            }

            return(this);
        }
Exemple #2
0
        /// <summary>
        /// Essentially creates a clone of the given section if its valid. Can be used to modify an existing Section.
        /// </summary>
        /// <param name="section">The section to modify.</param>
        internal SectionBuilder(Section section)
        {
            if (section != null)
            {
                _name      = section.Name;
                _isEnabled = section.IsEnabled;
                _comment   = Comment.Builder(section.Comment).Build();

                for (int i = 0; i < section.Properties().Count; i++)
                {
                    _properties.Add(Property.Builder(section.Properties()[i]).Build());
                }
            }
        }
Exemple #3
0
        private void GetProperty(string line, string sName, ref Comment comment)
        {
            if (line.PropertyIsValidAndUpdated(out var key, out var value, out var isEnabled))
            {
                AppendProperty(sName, Property
                               .Builder()
                               .WithKey(key)
                               .WithValue(value)
                               .WithComment(comment)
                               .IsEnable(isEnabled)
                               .Build());

                comment = Comment.Builder().Build();
            }
        }
Exemple #4
0
        /// <summary>
        /// Creates <see cref="Section"/> from the given text if it's valid.
        /// </summary>
        /// <param name="text">The text to parse.</param>
        /// <returns></returns>
        public SectionBuilder Parse(string text)
        {
            if (!string.IsNullOrWhiteSpace(text))
            {
                var foundSection = false;
                var comment      = Comment.Builder().Build();

                using (var en = text.SplitToLines().Select(l => l.Trim()).Where(l => l != "").GetEnumerator())
                {
                    while (en.MoveNext())
                    {
                        if (en.Current.CommentIsValidAndUpdated(ref comment))
                        {
                            continue;
                        }

                        if (en.Current.SectionIsValidAndUpdated(ref _name, ref _isEnabled))
                        {
                            if (foundSection)
                            {
                                break;
                            }

                            foundSection = true;
                            _comment     = comment;
                            comment      = Comment.Builder().Build();
                        }

                        if (en.Current.PropertyIsValidAndUpdated(out var key, out var value, out var isEnabled))
                        {
                            _properties.Add(Property
                                            .Builder()
                                            .WithKey(key)
                                            .WithValue(value)
                                            .WithComment(comment)
                                            .IsEnable(isEnabled)
                                            .Build());

                            comment = Comment.Builder().Build();
                        }
                    }
                }
            }

            return(this);
        }
        /// <summary>
        /// Read a <see cref="Section"/> from an ini file.
        /// </summary>
        /// <param name="file">The full path of the file to read from.</param>
        /// <param name="name">The name of the <see cref="Section"/> to read.</param>
        /// <returns>Returns the <see cref="Section"/> if its found.</returns>
        public static async Task <Section> ReadSectionAsync(string file, string name)
        {
            if (!file.IsValidFile())
            {
                return(null);
            }

            var section = Section.Builder().Build();
            var comment = Comment.Builder().Build();

            using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, DefaultOptions))
                using (var reader = new StreamReader(stream))
                {
                    string line;
                    while ((line = await reader.ReadLineAsync()) != null)
                    {
                        if (line.IsComment().isTrue)
                        {
                            comment = Comment.Builder().AppendLine(line).Build();
                            continue;
                        }

                        var sec = line.IsSection();
                        if (sec.isTrue)
                        {
                            if (section.Name.Equals(name))
                            {
                                return(section);
                            }

                            if (sec.sectionName.Equals(name))
                            {
                                section = Section
                                          .Builder()
                                          .WithName(sec.sectionName)
                                          .WithComment(comment)
                                          .IsEnable(sec.isEnable)
                                          .Build();
                            }

                            comment = Comment.Builder().Build();
                            continue;
                        }

                        var(isTrue, isEnabled, key, value) = line.IsProperty();
                        if (isTrue && section.Name.Equals(name))
                        {
                            section = Section
                                      .Builder(section)
                                      .AppendProperty(Property
                                                      .Builder()
                                                      .WithKey(key)
                                                      .WithValue(value)
                                                      .WithComment(comment)
                                                      .IsEnable(isEnabled)
                                                      .Build())
                                      .Build();
                        }
                        comment = Comment.Builder().Build();
                    }
                }

            return(section.IsEmpty ? null : section);
        }
        /// <summary>
        /// Writes the <see cref="IniDocument"/> object to disk.
        /// </summary>
        /// <param name="file">The full path to the file to write to.</param>
        /// <param name="sectionName">The section to create/update.</param>
        /// <param name="key">The property key to create/update</param>
        /// <param name="value">The property value to set.</param>
        /// <param name="updateProperty">If a property with the given key exists, should its value be updated or should a new property with the same key be created.</param>
        public static async Task WriteAsync(string file, string sectionName, string key, string value, bool updateProperty = false)
        {
            if (!file.IsValidPath())
            {
                throw new ArgumentException(InvalidFilePathMessage);
            }

            var dir = Path.GetDirectoryName(file);

            if (dir != null && !Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (!file.IsValidFile())
            {
                await Builder()
                .SetFile(file)
                .AppendSection(Section
                               .Builder()
                               .WithName(sectionName)
                               .AppendProperty(Property
                                               .Builder()
                                               .WithKey(key)
                                               .WithValue(value)
                                               .Build())
                               .Build())
                .Build()
                .WriteAsync();

                return;
            }

            var tmpFile = file + ".tmp";
            var cache   = new List <string>(DefaultBufferSize);
            var footer  = new StringBuilder();

            var isSectionFound = false;

            using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None, DefaultBufferSize, DefaultOptions))
                using (var reader = new StreamReader(stream))
                {
                    string line;
                    while ((line = await reader.ReadLineAsync()) != null)
                    {
                        if (cache.Capacity >= DefaultBufferSize)
                        {
                            await BackupAndResetCacheAsync();
                        }

                        if (line.IsHeader())
                        {
                            cache.Add(line);
                            continue;
                        }

                        if (line.IsFooter())
                        {
                            footer.AppendLine(line);
                            continue;
                        }

                        if (line.IsComment().isTrue)
                        {
                            cache.Add(line);
                            continue;
                        }

                        var sec = line.IsSection();
                        if (sec.isTrue && sec.sectionName.Equals(sectionName))
                        {
                            isSectionFound = true;
                            cache.Add(line);
                            continue;
                        }

                        var prop = line.IsProperty();
                        if (isSectionFound && prop.isTrue && prop.key.Equals(key))
                        {
                            if (updateProperty)
                            {
                                cache.Add($"{key}={value}");
                            }
                            else
                            {
                                cache.Add(line);
                                cache.Add($"{key}={value}");
                            }
                            continue;
                        }

                        cache.Add(line);
                    }
                }

            if (!isSectionFound)
            {
                cache.Add(sectionName.AsSection());
                cache.Add($"{key}={value}");
            }

            if (footer.Length > 0)
            {
                cache.Add(footer.ToString().Trim());
            }

            if (cache.Count > 0)
            {
                await BackupAndResetCacheAsync();
            }

            File.Delete(file);
            File.Move(tmpFile, file);

            async Task BackupAndResetCacheAsync()
            {
                using (var fs = new FileStream(tmpFile, FileMode.Append, FileAccess.Write, FileShare.None, DefaultBufferSize, DefaultOptions))
                    using (var sw = new StreamWriter(fs))
                    {
                        for (int i = 0; i < cache.Count; i++)
                        {
                            await sw.WriteLineAsync(cache[i]);
                        }
                    }
                cache.Clear();
                cache.Capacity = DefaultBufferSize;
            }
        }