Ini配置文件读写,增加备注功能

1.增加备注项写入

例:

#节点备注

A

#项备注

bbb=1

ccc=2

B

bbb=1

IniConfig2 ic = new IniConfig2();

//首次写入

if (!ic.CanRead())

{

ic.AddSectionReMarke("A", "节点备注");

ic.SetValue("A", "bbb", "1" );

ic.SetValue("A", "ccc", "2");

ic.SetValue("A", "ccc", "2");

ic.SetValue("B", "bbb", "1");

ic.AddItemReMarke("A","bbb", "项备注");

}

//获取值

string a = ic.GetValue("A", "bbb");

cs 复制代码
    /// <summary>
    /// 配置文件读写类,支持中文和注释保留
    /// 增加备注
    /// </summary>
    public class IniConfig2
    {
        //小结
        private class Section
        {
            public Section()
            {
                items = new List<ValueItem>();
                reMark = new List<string>();
            }
            public string name;//名称
            public List<ValueItem> items;//子项
            public List<string> reMark;//备注
        }
        //项目
        private class ValueItem
        {
            public ValueItem()
            {
                reMark = new List<string>();
            }
            public string key;//键
            public string value;//值
            public List<string> reMark;//备注
        }


        private const string DefaultFileName = "Config.ini";//默认文件
        private readonly string filePath;
        public IniConfig2() : this(DefaultFileName)
        {
        }
        public IniConfig2(string _fileName)
        {
            if (string.IsNullOrWhiteSpace(_fileName))
            {
                _fileName = DefaultFileName;
            }
            _fileName = _fileName.EndsWith(".ini", StringComparison.OrdinalIgnoreCase) ? _fileName : $"{_fileName}.ini";
            filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _fileName);
            Load();
        }

        public bool CanRead()
        {
            return File.Exists(filePath);
        }
        List<Section> lst_Section;
        private void Load()
        {
            lst_Section = new List<Section>();
            List<string> fileComments = new List<string>();
            fileComments.Clear();
            if (!File.Exists(filePath))
            {
                return;
            }
            using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8))
            {
                string _txt, _preSectio = "", _preKey = "";

                List<string> lst_reMarke = new List<string>();
                Section sec = null;
                while ((_txt = reader.ReadLine()) != null)
                {
                    _txt = _txt.Trim();
                    if (_txt == "")
                    {
                        continue;
                    }
                    if (_txt.StartsWith("#") || _txt.StartsWith(";"))
                    {
                        // 收集注释行
                        lst_reMarke.Add(_txt);
                    }
                    else if (_txt.StartsWith("[") && _txt.EndsWith("]"))
                    {
                        if (sec != null)
                        {
                            lst_Section.Add(sec);
                        }
                        sec = new Section();
                        //节名称
                        _preSectio = _txt.Substring(1, _txt.Length - 2).Trim();
                        sec.name = _preSectio;
                        // 保存小结前的注释
                        if (lst_reMarke.Count > 0)
                        {
                            sec.reMark = lst_reMarke.ToList();
                            lst_reMarke.Clear();
                        }
                    }
                    else
                    {
                        // 键=值
                        int index = _txt.IndexOf('=');
                        if (index > 0 && _preSectio != "")
                        {
                            string key = _txt.Substring(0, index).Trim();
                            string value = _txt.Substring(index + 1).Trim();
                            _preKey = key;
                            ValueItem content = new ValueItem();
                            content.key = _preKey;
                            content.value = value;
                            sec.items.Add(content);
                        }
                        else
                        {
                            ValueItem ct = sec.items.FirstOrDefault(p => p.key == _preKey);
                            if (ct != null)
                            {
                                ct.value += Environment.NewLine + _txt;
                            }
                        }

                        // 保存项注释
                        if (lst_reMarke.Count > 0)
                        {
                            ValueItem ct = sec.items.FirstOrDefault(p => p.key == _preKey);
                            if (ct != null)
                            {
                                ct.reMark = lst_reMarke.ToList();
                                lst_reMarke.Clear();
                            }
                        }
                    }
                }
                //数据读取完后,追加到lst
                if (sec != null)
                {
                    lst_Section.Add(sec);
                }
            }
        }

        public string GetValue(string section, string key)
        {
            ValueItem ct = lst_Section.FirstOrDefault(p => p.name == section)?.items.FirstOrDefault(p => p.key == key);
            if (ct != null)
            {
                return ct.value.Replace(Environment.NewLine, "");
            }
            else
            {
                return "";
            }
        }

        public void SetValue(string section, string key, string value)
        {
            Section nt = lst_Section.FirstOrDefault(p => p.name == section);
            if (nt != null)
            {
                ValueItem ct = nt.items.FirstOrDefault(p => p.key == key);
                if (ct != null)
                {
                    ct.value = value;
                }
                else
                {
                    ct = new ValueItem();
                    ct.key = key;
                    ct.value = value;
                    nt.items.Add(ct);
                }
            }
            else
            {
                nt = new Section();
                nt.name = section;
                ValueItem ct = new ValueItem();
                ct.key = key;
                ct.value = value;
                nt.items.Add(ct);
                lst_Section.Add(nt);
            }
            Save();
        }

        public void AddSectionReMarke(string section, string remarke)
        {
            Section nt = lst_Section.FirstOrDefault(p => p.name == section);
            if (nt != null)
            {
                nt.reMark.Add(remarke.StartsWith("#") ? remarke : "#" + remarke);
            }
            else
            {
                nt = new Section();
                nt.name = section;
                nt.reMark.Add(remarke.StartsWith("#") ? remarke : "#" + remarke);
                lst_Section.Add(nt);
            }
            Save();
        }
        public void AddItemReMarke(string section, string key, string remarke)
        {
            Section nt = lst_Section.FirstOrDefault(p => p.name == section);
            if (nt != null)
            {
                ValueItem ct = nt.items.FirstOrDefault(p => p.key == key);
                if (ct != null)
                {
                    ct.reMark.Add(remarke.StartsWith("#") ? remarke : "#" + remarke);
                }
                else
                {
                    ct = new ValueItem();
                    ct.key = key;
                    ct.reMark.Add(remarke.StartsWith("#") ? remarke : "#" + remarke);
                    lst_Section.Add(nt);
                }
            }
            else
            {
                nt = new Section();
                nt.name = section;
                ValueItem ct = new ValueItem();
                ct.key = key;
                ct.reMark.Add(remarke.StartsWith("#") ? remarke : "#" + remarke);
                lst_Section.Add(nt);
            }
            Save();
        }

        private void Save()
        {
            using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
            {
                // 写入各个section
                foreach (Section section in lst_Section)
                {
                    // 写入section前的注释
                    foreach (string comment in section.reMark)
                    {
                        writer.WriteLine(comment);
                    }


                    // 写入section
                    writer.WriteLine($"[{section.name}]");

                    // 写入键值对
                    foreach (ValueItem cnt in section.items)
                    {
                        //写备注

                        foreach (string comment in cnt.reMark)
                        {
                            writer.WriteLine(comment);
                        }

                        //写值
                        writer.WriteLine($"{cnt.key}={cnt.value}");
                    }
                    writer.WriteLine(); // 空行分隔不同的节
                }
            }
        }
    }
相关推荐
SeanQhl1 小时前
中文 Windows 上跑 Python 定时任务——编码、路径、控制台三个坑
windows·python·编码·效率工具·定时任务
Vex2une5 小时前
系统出问题不想重装?系统还原点创建与重置此电脑完整指南
windows·系统还原点·重置此电脑·系统还原怎么用·创建还原点·保留文件重置·系统保护开启
保卫大狮兄1 天前
2026中小制造企业轻量化ERP选型观察:产供销协同路线、上线周期与ROI分析
windows·microsoft·erp·生产管理
陈工大模型1 天前
MacOS 跨平台压缩包处理:从编码痛点到工程化落地的完整方案
windows·macos·缓存·电脑·策略模式·c盘清理
凌镜icecraft2 天前
我改文件扩展名的时候那个警告弹窗再也不会弹出来了
windows·c#·wpf·explorer
the3clipse2 天前
Windows 11 26H2 AI 功能使用指南:回顾、单击以执行与实时字幕
人工智能·windows·copilot+ pc·recall 回顾·单击以执行·实时字幕翻译·windows studio
the3clipse2 天前
Windows 11 26H2 账户登录与 Windows Hello 指南:并行验证、增强登录安全与无密码设置
windows·无密码登录·windows hello·增强登录安全性ess·pin与密码区别·动态锁·win11 26h2
承渊政道2 天前
Toonflow AI短剧教程:Windows部署、批量生成与角色一致性
人工智能·windows·cpolar·ai短剧·toonflow
钱栈up2 天前
微软商店把《我的世界》国区从 89 涨到 110.99:一个「小调价」里的平台定价权博弈
游戏·microsoft·raft
Summer-Bright3 天前
深度 | 决策模型抢滩:OpenAI 微软同周下场,大模型从生成文本转向输出概率判断
人工智能·microsoft·ai·微软·qwen·决策