我想从 ini 文件中获取部分列表。现在我的文件中只有一个部分,下面的代码返回空值。
我尝试了使用 GetSectionNamesListA 和 GetPrivateProfileSectionNames 的各种方法。他们似乎都没有帮助
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;
}
使用:
[DllImport("kernel32")]
static extern int GetPrivateProfileSectionNames(byte[] pszReturnBuffer, int nSize, string lpFileName);
尽管存在一个部分,但我仍然返回空值。
最简单的方法可能是使用像INI Parser这样的库
这是使用库的示例:
var parser = new FileIniDataParser();
IniData data = parser.ReadFile("file.ini");
foreach (var section in data.Sections)
{
Console.WriteLine(section.SectionName);
}
在您的情况下GetPrivateProfileSectionNames
,不提供部分名称,因为它需要文件的完整路径。如果你给它一个相对路径,它会尝试在 Windows 文件夹中找到它。
初始化文件的名称。如果此参数为 NULL,该函数将搜索 Win.ini 文件。如果此参数不包含文件的完整路径,系统将在 Windows 目录中搜索该文件。
解决这个问题的一种方法是使用Path.GetFullPath(path)
:
path = Path.GetFullPath(path);
此页面显示了以下内容的正确用法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');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句