Reputation: 300
I want to get the list of sections from an ini file.I have only one section in my file now and my below code is returning null.
I tried various methods using GetSectionNamesListA and GetPrivateProfileSectionNames. None of them seem to help
public string[] GetSectionNames(string path)
{
byte[] buffer = new byte[1024];
GetPrivateProfileSectionNames(buffer, buffer.Length, path);
string allSections = System.Text.Encoding.Default.GetString(buffer);
string[] sectionNames = allSections.Split('\0');
return sectionNames;
}
Using:
[DllImport("kernel32")]
static extern int GetPrivateProfileSectionNames(byte[] pszReturnBuffer, int nSize, string lpFileName);
I am getting null returned inspite of a section being present.
Upvotes: 1
Views: 9126
Reputation: 926
The easiest way might be to use a library like INI Parser
Here is an example using the library:
var parser = new FileIniDataParser();
IniData data = parser.ReadFile("file.ini");
foreach (var section in data.Sections)
{
Console.WriteLine(section.SectionName);
}
And in your case GetPrivateProfileSectionNames
doesn't give the section names because it expects the full path of the file. If you give it a relative path, it will try to find it in the Windows folder.
The name of the initialization file. If this parameter is NULL, the function searches the Win.ini file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.
One way to fix that is to use Path.GetFullPath(path)
:
path = Path.GetFullPath(path);
And this page shows the proper usage of GetPrivateProfileSectionNames
:
[DllImport("kernel32")]
static extern uint GetPrivateProfileSectionNames(IntPtr pszReturnBuffer, uint nSize, string lpFileName);
public static string[] SectionNames(string path)
{
path = Path.GetFullPath(path);
uint MAX_BUFFER = 32767;
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
if (bytesReturned == 0)
return null;
string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
Marshal.FreeCoTaskMem(pReturnedString);
//use of Substring below removes terminating null for split
return local.Substring(0, local.Length - 1).Split('\0');
}
Upvotes: 6