C#操作讀寫INI配置文件


一個完整的INI文件格式由節(section)、鍵(key)、值(value)組成。
示例如:
[section]
key1=value1
key2=value2
; 備注:value的值不要太長,理論上最多不能超過65535個字節。

在Windows程序開發中經常會遇到讀寫INI配置文件的情況,以下C#類封裝了對INI配置文件讀寫修改的操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace CRApp
{
    public class INIHelper
    {
        private string FilePath;
        public string Path
        {
            get { return this.FilePath; }
            set
            {
                if (value.Substring(0, 1) == "\\" || value.Substring(0, 1) == "/")
                {
                    this.FilePath = AppDomain.CurrentDomain + value;
                }
                else
                {
                    this.FilePath = value;
                }
            }
        }
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        public INIHelper(string _Path)
        {
            this.Path = _Path;
        }
        public void WriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.FilePath);
        }
        public string ReadValue(string Section, string Key)
        {
            try
            {
                StringBuilder temp = new StringBuilder();
                int i = GetPrivateProfileString(Section, Key, "", temp, -1, this.FilePath);
                return temp.ToString();
            }
            catch { return ""; }
        }
        public void RemoveKey(string Section, string Key)
        {
            WritePrivateProfileString(Section, Key, null, this.FilePath);
        }
        public bool RemoveSection(string Section)
        {
            return WritePrivateProfileString(Section, null, null, this.FilePath);
        }
        public bool Exists()
        {
            return System.IO.File.Exists(this.FilePath);
        }
    }
}

參考:
[1] WritePrivateProfileString 函數: https://baike.baidu.com/item/WritePrivateProfileString/9711454
[2] GetPrivateProfileString 函數: https://baike.baidu.com/item/GetPrivateProfileString/9642262


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM