Read all ini file values with GetPrivateProfileString

前端 未结 5 1925
轮回少年
轮回少年 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:32

    Dim MyString    As String = String.Empty
    Dim BufferSize As Integer = 1024 
    Dim PtrToString As IntPtr = IntPtr.Zero
    Dim RetVal As Integer
    RetVal = GetPrivateProfileSection(SectionName, PtrToString, BufferSize, FileNameAndPah)
    

    If our function call succeeds, we will get the result in PtrToString memory address and RetVal will contain the length of the string in PtrToString. Else if this function failed due to the lack of enough BufferSize Then RetVal will contain BufferSize - 2. So we can check it and call this function again with larger BufferSize.

    'Now, here is how we can get the string from memory address.

    MyString = Marshal.PtrToStringAuto(PtrToString, RetVal - 1)
    

    'Here i use " RetVal - 1 " to avoid the extra null string.

    ' Now, we need to split the string where null chars coming.

    Dim MyStrArray() As String = MyString.Split(vbNullChar)
    

    So this array contains all your keyvalue pair in that specific section. And dont forget to free up the memory

    Marshal.FreeHGlobal(PtrToString)
    

提交回复
热议问题