//************************************************************************
// author: yuzhengyang
// date: 2018.3.27 - 2018.6.3
// desc: 工具描述
// Copyright (c) yuzhengyang. All rights reserved.
//************************************************************************
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Azylee.Core.IOUtils.TxtUtils
{
public class IniTool
{
/*
* 针对INI文件的API操作方法,其中的节点(Section)、键(KEY)都不区分大小写
* 如果指定的INI文件不存在,会自动创建该文件。
*
* CharSet定义的时候使用了什么类型,在使用相关方法时必须要使用相应的类型
* 例如 GetPrivateProfileSectionNames声明为CharSet.Auto,那么就应该使用 Marshal.PtrToStringAuto来读取相关内容
* 如果使用的是CharSet.Ansi,就应该使用Marshal.PtrToStringAnsi来读取内容
*
*/
#region API声明
///
/// 获取所有节点名称(Section)
///
/// 存放节点名称的内存地址,每个节点之间用\0分隔
/// 内存大小(characters)
/// Ini文件
/// 内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);
///
/// 获取某个指定节点(Section)中所有KEY和Value
///
/// 节点名称
/// 返回值的内存地址,每个之间用\0分隔
/// 内存大小(characters)
/// Ini文件
/// 内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);
///
/// 读取INI文件中指定的Key的值
///
/// 节点名称。如果为null,则读取INI中所有节点名称,每个节点名称之间用\0分隔
/// Key名称。如果为null,则读取INI中指定节点中的所有KEY,每个KEY之间用\0分隔
/// 读取失败时的默认值
/// 读取的内容缓冲区,读取之后,多余的地方使用\0填充
/// 内容缓冲区的长度
/// INI文件名
/// 实际读取到的长度
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName);
//另一种声明方式,使用 StringBuilder 作为缓冲区类型的缺点是不能接受\0字符,会将\0及其后的字符截断,
//所以对于lpAppName或lpKeyName为null的情况就不适用
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);
//再一种声明,使用string作为缓冲区的类型同char[]
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName);
///
/// 将指定的键值对写到指定的节点,如果已经存在则替换。
///
/// 节点,如果不存在此节点,则创建此节点
/// Item键值对,多个用\0分隔,形如key1=value1\0key2=value2
/// 如果为string.Empty,则删除指定节点下的所有内容,保留节点
/// 如果为null,则删除指定节点下的所有内容,并且删除该节点
///
/// INI文件
/// 是否成功写入
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)] //可以没有此行
private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);
///
/// 将指定的键和值写到指定的节点,如果已经存在则替换
///
/// 节点名称
/// 键名称。如果为null,则删除指定的节点及其所有的项目
/// 值内容。如果为null,则删除指定节点中指定的键。
/// INI文件
/// 操作是否成功
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
#endregion
#region 封装
///
/// 读取INI文件中指定INI文件中的所有节点名称(Section)
///
/// Ini文件
/// 所有节点,没有内容返回string[0]
public static string[] GetAllSectionNames(string iniFile)
{
uint MAX_BUFFER = 32767; //默认为32767
string[] sections = new string[0]; //返回值
//申请内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
if (bytesReturned != 0)
{
//读取指定内存的内容
string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();
//每个节点之间用\0分隔,末尾有一个\0
sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
//释放内存
Marshal.FreeCoTaskMem(pReturnedString);
return sections;
}
///
/// 获取INI文件中指定节点(Section)中的所有条目(key=value形式)
///
/// Ini文件
/// 节点名称
/// 指定节点中的所有项目,没有内容返回string[0]
public static string[] GetAllItems(string iniFile, string section)
{
//返回值形式为 key=value,例如 Color=Red
uint MAX_BUFFER = 32767; //默认为32767
string[] items = new string[0]; //返回值
//分配内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile);
if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
{
string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
Marshal.FreeCoTaskMem(pReturnedString); //释放内存
return items;
}
///
/// 获取INI文件中指定节点(Section)中的所有条目的Key列表
///
/// Ini文件
/// 节点名称
/// 如果没有内容,反回string[0]
public static string[] GetAllItemKeys(string iniFile, string section)
{
string[] value = new string[0];
const int SIZE = 1024 * 10;
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
char[] chars = new char[SIZE];
uint bytesReturned = GetPrivateProfileString(section, null, null, chars, SIZE, iniFile);
if (bytesReturned != 0)
{
value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
chars = null;
return value;
}
///
/// 在INI文件中,将指定的键值对写到指定的节点,如果已经存在则替换
///
/// INI文件
/// 节点,如果不存在此节点,则创建此节点
/// 键值对,多个用\0分隔,形如key1=value1\0key2=value2
///
public static bool WriteItems(string iniFile, string section, string items)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
if (string.IsNullOrEmpty(items))
{
throw new ArgumentException("必须指定键值对", "items");
}
return WritePrivateProfileSection(section, items, iniFile);
}
///
/// 在INI文件中,删除指定节点中的指定的键。
///
/// INI文件
/// 节点
/// 键
/// 操作是否成功
public static bool DeleteKey(string iniFile, string section, string key)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称", "key");
}
return WritePrivateProfileString(section, key, null, iniFile);
}
///
/// 在INI文件中,删除指定的节点。
///
/// INI文件
/// 节点
/// 操作是否成功
public static bool DeleteSection(string iniFile, string section)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
return WritePrivateProfileString(section, null, null, iniFile);
}
///
/// 在INI文件中,删除指定节点中的所有内容。
///
/// INI文件
/// 节点
/// 操作是否成功
public static bool EmptySection(string iniFile, string section)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
return WritePrivateProfileSection(section, string.Empty, iniFile);
}
///
/// 测试
///
private void Test()
{
string file = "F:\\TestIni.ini";
//写入/更新键值
WriteValue(file, "Desktop", "Color", "Red");
WriteValue(file, "Desktop", "Width", "3270");
WriteValue(file, "Toolbar", "Items", "Save,Delete,Open");
WriteValue(file, "Toolbar", "Dock", "True");
//写入一批键值
WriteItems(file, "Menu", "File=文件\0View=视图\0Edit=编辑");
//获取文件中所有的节点
string[] sections = GetAllSectionNames(file);
//获取指定节点中的所有项
string[] items = GetAllItems(file, "Menu");
//获取指定节点中所有的键
string[] keys = GetAllItemKeys(file, "Menu");
//获取指定KEY的值
string value = GetValue(file, "Desktop", "color", null);
//删除指定的KEY
DeleteKey(file, "desktop", "color");
//删除指定的节点
DeleteSection(file, "desktop");
//清空指定的节点
EmptySection(file, "toolbar");
}
#endregion
#region 写入方法
[Obsolete]
///
/// 在INI文件中,指定节点写入指定的键及值。如果已经存在,则替换。如果没有则创建。
///
/// INI文件
/// 节点
/// 键
/// 值
/// 操作是否成功
public static bool WriteValue(string iniFile, string section, string key, string value)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称", "key");
}
if (value == null)
{
throw new ArgumentException("值不能为null", "value");
}
return WritePrivateProfileString(section, key, value, iniFile);
}
public static bool Set(string iniFile, string section, string key, string value) { return WriteValue(iniFile, section, key, value); }
public static bool Set(string iniFile, string section, string key, int value) { return WriteValue(iniFile, section, key, value.ToString()); }
public static bool Set(string iniFile, string section, string key, long value) { return WriteValue(iniFile, section, key, value.ToString()); }
public static bool Set(string iniFile, string section, string key, bool value) { return WriteValue(iniFile, section, key, value ? "true" : "false"); }
#endregion
#region 读取方法
[Obsolete]
///
/// 读取INI文件中指定KEY的字符串型值
///
/// Ini文件
/// 节点名称
/// 键名称
/// 如果没此KEY所使用的默认值
/// 读取到的值
public static string GetValue(string iniFile, string section, string key, string defaultValue)
{
string value = defaultValue;
const int SIZE = 1024 * 10;
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称(key)", "key");
}
StringBuilder sb = new StringBuilder(SIZE);
uint bytesReturned = GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile);
if (bytesReturned != 0)
{
value = sb.ToString();
}
sb = null;
return value;
}
public static string GetString(string iniFile, string section, string key, string defaultValue)
{
return GetValue(iniFile, section, key, defaultValue);
}
public static bool GetBool(string iniFile, string section, string key, bool defaultValue)
{
string value = GetString(iniFile, section, key, "");
if (value.ToLower() == "true") return true;
if (value.ToLower() == "false") return false;
return defaultValue;
}
public static int GetInt(string iniFile, string section, string key, int defaultValue)
{
string value = GetString(iniFile, section, key, defaultValue.ToString());
if (int.TryParse(value, out int result)) return result;
return defaultValue;
}
public static long GetLong(string iniFile, string section, string key, long defaultValue)
{
string value = GetString(iniFile, section, key, defaultValue.ToString());
if (long.TryParse(value, out long result)) return result;
return defaultValue;
}
#endregion
}
}