帮助类可以拿过去直接用
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace Mdm.Lite.Common.Helpers
{
public static class IniHelper
{
// 声明INI文件的写操作函数 WritePrivateProfileString()
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
// 声明INI文件的读操作函数 GetPrivateProfileString()
[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
private static extern uint GetPrivateProfileStringA(string section, string key,
string def, Byte[] retVal, int size, string filePath);
///
/// 为某个节写入key
/// 如果这个key已存在,那么久是更新此key
///
///
///
///
///
public static void Write(string section, string key, string value,string sPath)
{
// section=配置节,key=键名,value=键值,path=路径
WritePrivateProfileString(section, key, value, sPath);
}
///
/// 读取某个key的值
///
///
///
///
///
public static string ReadValue(string section, string key, string sPath)
{
// 每次从ini中读取多少字节 (最多2048个字符)
StringBuilder temp = new StringBuilder(2048);
// section=配置节,key=键名,temp=上面,读取该键名的值最大长度,path=路径
GetPrivateProfileString(section, key, "", temp, 2048, sPath);
return temp.ToString();
}
///
/// 读取所有的节
///
///
///
public static List ReadSections(string iniFilename)
{
List result = new List();
Byte[] buf = new Byte[65536];
uint len = GetPrivateProfileStringA(null, null, null, buf, buf.Length, iniFilename);
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;
}
///
/// 读取节下所有的keys
///
///
///
///
public static List ReadKeys(string SectionName, string iniFilename)
{
List result = new List();
Byte[] buf = new Byte[65536];
uint len = GetPrivateProfileStringA(SectionName, null, null, buf, buf.Length, iniFilename);
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;
}
///
/// 删除某个节下的key
///
///
///
///
public static void DeleteKey(string section, string key, string sPath)
{
WritePrivateProfileString(section, key, null, sPath);
}
///
/// 删除某个节
///
///
///
public static void DeleteSection(string section, string sPath)
{
WritePrivateProfileString(section, null, null, sPath);
}
}
}
了解ini文件的格式:
[section]
key=value
以上为一个ini文件的基本格式,section 是段落名,key是键名,value为键所对应的值。英文分号后面所有内容为注释内容
用法如代码所示:注意只可以修改对应的value值,不可以修改段落名或者key,如果有需要修改,那么就是先把原来的段落内容临时存下来,新建个段落,把要修改的段落的内容新增到新段落中,然后删除老段落。