LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C# 配置ini文件读、写介绍

admin
2025年7月14日 23:19 本文热度 72

      ini 文件是一种经典的配置文件格式,在 Windows 系统中有着广泛的应用。特别在系统开发时,常用使用ini文件来配置系统参数;

1、配置格式如下:
[Setting]ServerIp=127.0.0.1Port=3306
[Node2]Item1=valueItem2=value   
2、函数调用:
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");

笔者整理了一些常用方法,附帮助类如下:

 /// <summary>/// Ini文件读写函数/// </summary>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键名值     /// <summary>    /// 读取string字符串     /// </summary>    /// <param name="sectionName">节点名</param>    /// <param name="keyName">键名</param>    /// <param name="defaultValue"></param>    /// <returns></returns>    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);//使用utf-8编码读取 解决乱码问题        }        catch (Exception)        {            return "";        }    }
    /// <summary>    /// 读取int数值    /// </summary>    /// <param name="sectionName">节点名</param>    /// <param name="keyName">键名</param>    /// <param name="value"></param>    /// <returns></returns>    public int ReadInteger(string sectionName, string keyName, int value)    {        return GetPrivateProfileInt(sectionName, keyName, value, m_szIniFilePath);    }
    /// <summary>    /// 读bool取布尔值    /// </summary>    /// <param name="sectionName"></param>    /// <param name="keyName"></param>    /// <param name="defaultValue"></param>    /// <param name="path"></param>    /// <returns></returns>    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 获取节点名称列表    /// <summary>    /// 获取节点名称列表    /// </summary>    /// <param name="path"></param>    /// <returns></returns>    public List<stringGetAllSectionNames()    {        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 获取某个节点下所有键名、值            /// <summary>    /// 获取某个节点下所有键名与值    /// </summary>    /// <param name="section">指定的节名称</param>    /// <param name="KeysList">Key键名列表</param>    /// <param name="KeysValueList">值列表</param>           /// <returns></returns>    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);//Key\Value信息        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[] { '=' });//Key=Value格式的配置信息            //Value字符串中含有=的处理,            //一、Value加"",先对""处理            //二、Key后续的都为Value            if (item.Length > 2)            {                keys[i] = item[0].Trim();                values[i] = result[i].Substring(keys[i].Length + 1);            }            if (item.Length == 2)//Key=Value            {                keys[i] = item[0].Trim();                values[i] = item[1].Trim();            }            else if (item.Length == 1)//Key=            {                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 获取节点键值列表    /// <summary>    /// 获取节点键值列表    /// </summary>    /// <param name="section">指定的节名称</param>    /// <returns></returns>    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 删除操作
    /// <summary>    /// 清空Ini文件    /// </summary>    public void ClearAll()    {        List<string> Sections = GetAllSectionNames();        foreach (var sec in Sections)        {            EraseSection(sec);        }    }
    /// <summary>    /// 清除指定节点    /// </summary>    /// <param name="ClearSec"></param>    public void ClearSection(List<string> ClearSec)    {        foreach (var sec in ClearSec)        {            EraseSection(sec);        }    }
    /// <summary>    /// 保留指定节点,其它节点全部清除    /// </summary>    /// <param name="szNotClearSec"></param>    public void ClearFileNotInclude(string szNotClearSec)    {        List<string> Sections = GetAllSectionNames();        Sections.Remove(szNotClearSec);        foreach (var sec in Sections)        {            EraseSection(sec);        }    }
    /// <summary>    /// 删除节点下所有键值    /// </summary>    /// <param name="sectionName"></param>    /// <param name="path"></param>    public bool EraseSection(string sectionName)    {        bool RetState = false;        try        {            WritePrivateProfileString(sectionName, nullnull, m_szIniFilePath);            RetState = true;        }        catch (Exception)        {            RetState = false;        }        return RetState;    }
    /// <summary>    /// 删除指定健值    /// </summary>    /// <param name="sectionName"></param>    /// <param name="keyName"></param>    /// <param name="path"></param>    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键名值            /// <summary>    /// 写string字符串    /// </summary>    /// <param name="sectionName">节点名</param>    /// <param name="keyName">键名</param>    /// <param name="value"></param>    public void WriteString(string sectionName, string keyName, string value)    {        WritePrivateProfileString(sectionName, Encoding.UTF8.GetBytes(keyName), Encoding.UTF8.GetBytes(value), m_szIniFilePath);    }
    /// <summary>    /// 写Int数值    /// </summary>    /// <param name="sectionName">节点名</param>    /// <param name="keyName">键名</param>    /// <param name="value"></param>    /// <returns></returns>    public void WriteInteger(string sectionName, string keyName, int value)    {        WritePrivateProfileString(sectionName, Encoding.UTF8.GetBytes(keyName), Encoding.UTF8.GetBytes(value.ToString()), m_szIniFilePath);    }
    /// <summary>    /// 写bool布尔值    /// </summary>    /// <param name="sectionName">节点名</param>    /// <param name="keyName">键名</param>    /// <param name="value"></param>    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 动态添加节点、键名、值    /// <summary>    /// 动态添加一个新节点、键名、值    /// </summary>    /// <param name="section"></param>    /// <param name="keyList"></param>    /// <param name="valueList"></param>    /// <param name="path"></param>    /// <returns></returns>    public bool AddNewSectionWithKeyValues(string section, List<string> keyList, List<string> valueList)    {        bool bRst = true;        //判断Section是否已经存在;        if (GetAllSectionNames().Contains(section))        {            return false;        }
        //判断keyList键名是否有重复;        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;    }
    /// <summary>    /// 在指定的一个节点下添加键值    /// </summary>    /// <param name="section"></param>    /// <param name="keyName"></param>    /// <param name="keyValue"></param>    /// <returns></returns>    public bool AddSectionWithKeyValues(string section, string keyName, string keyValue)    {        bool bRst = true;        //判断keyList键名是否有重复;        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

}
/// <summary>/// Ini节点列表Model/// </summary>public class IniSectionModel{    public string Sections { getset; } //节点    public string KeyName { getset; } //键名    public string Value { getset; } //值
}


阅读原文:原文链接


该文章在 2025/7/15 10:44:24 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved