【c#基础】读取和修改ini文件

本文介绍了如何使用C#编程语言操作Ini文件,包括读取value、修改value、删除key和section,以及提供了一系列系统调用来实现这些功能,并展示了IniFiles类的实例和接口设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ini文件的格式

[section]//节点
key=value//键=值

本文主要介绍.ini文件的读取value、修改value、删除value、删除key、删除section、清空key

系统调用

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]     //可以没有此行  
private static extern bool WritePrivateProfileSection(string retsection, string key, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
[DllImport("kernel32", CharSet = CharSet.Unicode)]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

创建IniFiles类

class  IniFiles
{
      string iniPath;//ini文件路径
        /// <summary> 
        /// 构造方法 
        /// </summary> 
        /// <param name="INIPath">文件路径</param> 
        public IniFiles(string INIPath)
        {
            iniPath = INIPath;
        }
        public IniFiles() { }
        /// <summary> 
        /// 验证文件是否存在 
        /// </summary> 
        /// <returns>布尔值</returns> 
        public bool ExistINIFile()
        {
            return File.Exists(iniPath);
        }
}

类中方法

  1. 写入数据
/// <summary> 
/// 写入.ini文件
/// </summary> 
public void IniWriteValue(string section, string key, string value)
{
    WritePrivateProfileString(section, key, value, iniPath);
}
/// <summary>
/// 指定字符集写入.ini文件
/// </summary>
/// <param name="encoding">字符集</param>
public void IniWriteValue(string section, string key, string value,Encoding encoding)
{
    byte[] retSection = encoding.GetBytes(section);
    byte[] retKey = encoding.GetBytes(key);
    byte[] retVal = encoding.GetBytes(value);
    WritePrivateProfileString(retSection, retKey, retVal, iniPath);
}
  1. 读取数据
/// <summary> 
/// 读出INI文件 
/// </summary> 
/// <param name="section">节点</param> 
/// <param name="key">键</param> 
public string IniReadValue(string section, string key)
{
    StringBuilder temp = new StringBuilder(SIZE_STRING_BUILDER);
    int i = GetPrivateProfileString(section, key, "", temp, SIZE_STRING_BUILDER, iniPath);
    return temp.ToString();
}
/// <summary>
/// 读取全部的节点信息,这里只能是节点的单个解析
/// </summary>
/// <returns></returns>
public List<string> ReadAllSections()
{
    List<string> result = new List<string>();
    Byte[] buf = new Byte[SIZE_LONG_BUFFER];
    int len = GetPrivateProfileString(null, null, null, buf, SIZE_LONG_BUFFER, iniPath);
    int j = 0;
    for (int i = 0; i < len; i++)
        if (buf[i] == 0)
        {
            result.Add(Encoding.Default.GetString(buf, j, i - j));
            j = i + 1;
        }
    return result;
}
public  List<string> ReadKeys(string section)
{
    List<string> result = new List<string>();
    StringBuilder sb = new StringBuilder(SIZE_STRING_BUILDER);
    int len = GetPrivateProfileString(section, null, null, sb, SIZE_STRING_BUILDER, iniPath);
    int j = 0;
    for (int i = 0; i < len; i++)
        if (sb[i] == 0)
        {
            result.Add(sb[i].ToString());
            j = i + 1;
        }
    return result;
}
/// <summary>
/// 读取double
/// </summary>
/// <param name="section">节点</param>
/// <param name="name">键</param>
/// <param name="def">默认值</param>
/// <returns></returns>
public double ReadDouble(string section, string name, double def)
{
    StringBuilder vRetSb = new StringBuilder(SIZE_STRING_BUILDER);
    GetPrivateProfileString(section, name, "", vRetSb, SIZE_STRING_BUILDER, iniPath);
    if (vRetSb.Length < 1)
    {
        return def;
    }
    return Convert.ToDouble(vRetSb.ToString());
}
  1. 删除节点
/// <summary>
/// 删除指定key的value
/// </summary>
/// <param name="section">段落</param>
/// <param name="key">键</param>
public void IniDeleteKey(string section, string key)
{
   IniWriteValue(section, key, null);
}
/// <summary>
/// 清空指定节点内的所有key、value
/// </summary>
/// <param name="section">节点</param>
public void IniDeleteSection(string section)
{
   IniWriteValue(section, null, null);
}
  1. 清空节点
/// <summary>
/// 清空指定节点
/// </summary>
/// <param name="section">段落</param>
public void IniEmptySection(string section)
{
    WritePrivateProfileSection(section, string.Empty,  iniPath);
}
  1. 读取全部节点
public static Dictionary<string, Dictionary<string, string>> ParseIniFile()
{
    Dictionary<string, Dictionary<string, string>> iniData =
        new Dictionary<string, Dictionary<string, string>>();

    using (StreamReader reader = new StreamReader(iniPath))
    {
        string section = "";
        Dictionary<string, string> sectionData = 
        new Dictionary<string, string>();

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine().Trim();

            if (line.StartsWith("[") && line.EndsWith("]"))
            {
                // 开始一个新的节
                section = line.Substring(1, line.Length - 2);
                sectionData = new Dictionary<string, string>();
                iniData[section] = sectionData;
            }
            else if (line.Contains("="))
            {
                // 解析键值对
                string[] parts = line.Split('=');
                string key = parts[0].Trim();
                string value = parts[1].Trim();
                sectionData[key] = value;
            }
        }
    }
    return iniData;
}

界面展示

  1. 读取全部节点
lbxINI.Items.Clear();
Dictionary<string, Dictionary<string, string>> dict = IniFiles.ParseIniFile();
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, Dictionary<string, string>> sections in dict)
{
    sb.Append("-  " + sections.Key);
    lbxINI.Items.Add(sb.ToString());
    sb.Clear();
    Dictionary<string, string> keyValues = sections.Value;
    foreach (KeyValuePair<string, string> kvp in keyValues)
    {
        sb.Append( kvp.Key+ ": "+ kvp.Value);
        lbxINI.Items.Add(sb.ToString());
        sb.Clear();
    }
    lbxINI.Items.Add("");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值