Read all ini file values with GetPrivateProfileString

前端 未结 5 1911
轮回少年
轮回少年 2020-12-30 08:04

I need a way to read all sections/keys of ini file in a StringBuilder variable:

[DllImport(\"kernel32.dll\")]
private static extern int GetPrivateProfileStri         


        
5条回答
  •  长发绾君心
    2020-12-30 08:47

    These routines will read an entire INI section, and either return the section as a collection of raw strings where each entry is a single line in the INI file (useful if you're using the INI structure but don't necessarily have an =), and another that returns a collection of keyvalue pairs for all of the entries in the section.

        [DllImport("kernel32.dll")]
        public static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);
    
        // ReSharper disable once ReturnTypeCanBeEnumerable.Global
        public static string[] GetIniSectionRaw(string section, string file) {
            string[] iniLines;
            GetPrivateProfileSection(section, file, out iniLines);
            return iniLines;
        }
    
        ///  Return an entire INI section as a list of lines.  Blank lines are ignored and all spaces around the = are also removed. 
        /// [Section]
        /// INI File
        ///  List of lines 
        public static IEnumerable> GetIniSection(string section, string file) {
            var result = new List>();
            string[] iniLines;
            if (GetPrivateProfileSection(section, file, out iniLines)) {
                foreach (var line in iniLines) {
                    var m = Regex.Match(line, @"^([^=]+)\s*=\s*(.*)");
                    result.Add(m.Success
                                   ? new KeyValuePair(m.Groups[1].Value, m.Groups[2].Value)
                                   : new KeyValuePair(line, ""));
                }
            }
    
            return result;
        }
    

提交回复
热议问题