ini 文件是一种经典的配置文件格式,在 Windows 系统中有着广泛的应用。特别在系统开发时,常用使用ini文件来配置系统参数;[Setting]ServerIp=127.0.0.1Port=3306
[Node2]Item1=valueItem2=value   
string ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SysConfig.ini");
IniFileHelper IntObj = new IniFileHelper(ConfigPath);
string ServerIp = IntObj.ReadString("Setting", "ServerIp");
IntObj.WriteString("Setting", "ServerIp", "192.168.0.12");
IntObj.DeleteKey("Setting", "Port");
 public class CIniFileHelper{    #region Windows ini文件API函数加载          [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Ansi)]    private static extern long WritePrivateProfileString(string section, byte[] key, byte[] val, string filePath);
    [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Ansi)]    private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
    [DllImport("kernel32")]    private static extern int GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName);
    [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames", CharSet = CharSet.Ansi)]    private static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, int nSize, string filePath);
    [DllImport("KERNEL32.DLL ", EntryPoint = "GetPrivateProfileSection", CharSet = CharSet.Ansi)]    private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string filePath);    #endregion
    private static CIniFileHelper handle = null;    public static CIniFileHelper Handle    {        get        {            if (handle == null)            {                handle = new CIniFileHelper(m_szIniFilePath);            }            return handle;        }    }
    public static string m_szIniFilePath;
    public CIniFileHelper(string _szIniFilePath)    {        m_szIniFilePath = _szIniFilePath;    }
    #region 读Ini键名值                                 public string ReadString(string sectionName, string keyName, string defaultValue = "")    {        try        {            const int MaxSize = 1024 * 1024 * 10;            byte[] Buffer = new byte[MaxSize];            StringBuilder temp = new StringBuilder(MaxSize);            int bufLen = GetPrivateProfileString(sectionName, keyName, defaultValue, Buffer, MaxSize, m_szIniFilePath);            return Encoding.UTF8.GetString(Buffer, 0, bufLen);        }        catch (Exception)        {            return "";        }    }
                                public int ReadInteger(string sectionName, string keyName, int value)    {        return GetPrivateProfileInt(sectionName, keyName, value, m_szIniFilePath);    }
                                    public bool ReadBoolean(string sectionName, string keyName, bool defaultValue = false)    {        int temp = defaultValue ? 1 : 0;
        int result = GetPrivateProfileInt(sectionName, keyName, temp, m_szIniFilePath);
        return (result == 0 ? false : true);    }
    #endregion
    #region 获取节点、键名、值列表
    #region 获取节点名称列表                        public List<string> GetAllSectionNames()    {        List<string> sectionList = new List<string>();        try        {            int MAX_BUFFER = 32767;            IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);            int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, m_szIniFilePath);            if (bytesReturned != 0)            {                string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();                Marshal.FreeCoTaskMem(pReturnedString);                sectionList.AddRange(local.Substring(0, local.Length - 1).Split('\0'));            }        }        catch (Exception)        {            sectionList = new List<string>();        }        return sectionList;    }    #endregion    
    #region 获取某个节点下所有键名、值                                        public int GetAllKeyValues(string section, out List<string> KeysList, out List<string> KeysValueList)    {        KeysList = new List<string>();        KeysValueList = new List<string>();
        byte[] b = new byte[65535];        GetPrivateProfileSection(section, b, b.Length, m_szIniFilePath);        string s = System.Text.Encoding.UTF8.GetString(b);        string[] tmp = s.Split((char)0);        List<string> result = new List<string>();        foreach (string r in tmp)        {            if (r != string.Empty)                result.Add(r);        }        string[] keys = new string[result.Count];        string[] values = new string[result.Count];        for (int i = 0; i < result.Count; i++)        {            string[] item = result[i].Split(new char[] { '=' });                                                if (item.Length > 2)            {                keys[i] = item[0].Trim();                values[i] = result[i].Substring(keys[i].Length + 1);            }            if (item.Length == 2)            {                keys[i] = item[0].Trim();                values[i] = item[1].Trim();            }            else if (item.Length == 1)            {                keys[i] = item[0].Trim();                values[i] = "";            }            else if (item.Length == 0)            {                keys[i] = "";                values[i] = "";            }        }        KeysList = keys.ToList<string>();        KeysValueList = values.ToList<string>();        return result.Count;    }    #endregion
    #region 获取节点键值列表                        public List<IniSectionModel> GetAllKeyValueList(string section)    {        List<IniSectionModel> RetList = new List<IniSectionModel>();        try        {            List<string> KeysList = new List<string>();            List<string> KeysValueList = new List<string>();            int RetNum = GetAllKeyValues(section, out KeysList, out KeysValueList);            if (KeysList.Count > 0 && KeysValueList.Count > 0 && KeysList.Count == KeysValueList.Count)            {                for (int i = 0; i < KeysList.Count; i++)                {                    IniSectionModel Node = new IniSectionModel();                    Node.Sections = section;                    Node.KeyName = KeysList[i];                    Node.Value = KeysValueList[i];                    RetList.Add(Node);                }            }        }        catch (Exception)        {            RetList = new List<IniSectionModel>();        }        return RetList;    }    #endregion
    #endregion
    #region 删除操作
                public void ClearAll()    {        List<string> Sections = GetAllSectionNames();        foreach (var sec in Sections)        {            EraseSection(sec);        }    }
                    public void ClearSection(List<string> ClearSec)    {        foreach (var sec in ClearSec)        {            EraseSection(sec);        }    }
                    public void ClearFileNotInclude(string szNotClearSec)    {        List<string> Sections = GetAllSectionNames();        Sections.Remove(szNotClearSec);        foreach (var sec in Sections)        {            EraseSection(sec);        }    }
                        public bool EraseSection(string sectionName)    {        bool RetState = false;        try        {            WritePrivateProfileString(sectionName, null, null, m_szIniFilePath);            RetState = true;        }        catch (Exception)        {            RetState = false;        }        return RetState;    }
                            public bool DeleteKey(string sectionName, string keyName)    {        bool RetState = false;        try        {            WritePrivateProfileString(sectionName, Encoding.UTF8.GetBytes(keyName), null, m_szIniFilePath);            RetState = true;        }        catch (Exception)        {            RetState = false;        }        return RetState;    }
    #endregion
    #region 写入(更新&添加)Ini键名值                                    public void WriteString(string sectionName, string keyName, string value)    {        WritePrivateProfileString(sectionName, Encoding.UTF8.GetBytes(keyName), Encoding.UTF8.GetBytes(value), m_szIniFilePath);    }
                                public void WriteInteger(string sectionName, string keyName, int value)    {        WritePrivateProfileString(sectionName, Encoding.UTF8.GetBytes(keyName), Encoding.UTF8.GetBytes(value.ToString()), m_szIniFilePath);    }
                            public void WriteBoolean(string sectionName, string keyName, bool value)    {        string temp = value ? "1 " : "0 ";        WritePrivateProfileString(sectionName, Encoding.UTF8.GetBytes(keyName), Encoding.UTF8.GetBytes(temp), m_szIniFilePath);    }    #endregion
    #region 动态添加节点、键名、值                                    public bool AddNewSectionWithKeyValues(string section, List<string> keyList, List<string> valueList)    {        bool bRst = true;                if (GetAllSectionNames().Contains(section))        {            return false;        }
                List<string> listA = keyList.Distinct().ToList();        if (listA.Count != keyList.Count)        {            return false;        }
                for (int i = 0; i < keyList.Count; i++)        {            WriteString(section, keyList[i], valueList[i]);        }        return bRst;    }
                                public bool AddSectionWithKeyValues(string section, string keyName, string keyValue)    {        bool bRst = true;                List<string> KeysList = new List<string>();        List<string> KeysValueList = new List<string>();        int RetNum = GetAllKeyValues(section, out KeysList, out KeysValueList);
        if (KeysList.Contains(keyName))        {            return false;        }
                WriteString(section, keyName, keyValue);        return bRst;    }    #endregion
}
public class IniSectionModel{    public string Sections { get; set; }     public string KeyName { get; set; }     public string Value { get; set; } 
}
阅读原文:原文链接
该文章在 2025/7/15 10:44:24 编辑过