/// <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<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 获取某个节点下所有键名、值
/// <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, null, null, 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 { get; set; } //节点
public string KeyName { get; set; } //键名
public string Value { get; set; } //值
}
C#读写的类
最新推荐文章于 2026-06-20 15:56:51 发布

1817

被折叠的 条评论
为什么被折叠?



