c# ini读写操作
ini读写代码详解实例,有很详细注释,保证满意; 预览截取一部分代码: /// /// 读取INI文件中指定INI文件中的所有节点名称(Section) /// /// Ini文件 /// 所有节点,没有内容返回string[0] public static string[] INIGetAllSectionNames(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[] INIGetAllItems(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; } 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[] INIGetAllItems(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; }
用户评论