【问题标题】:How to get All Section Names from ini file如何从ini文件中获取所有部分名称
【发布时间】:2019-10-04 15:54:00
【问题描述】:

我想从 ini 文件中获取节列表。我的文件中现在只有一个节,我的下面的代码返回 null。

我尝试了使用 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);

尽管存在一个部分,但我返回 null。

【问题讨论】:

  • 人们还在使用ini文件?!
  • 大声笑@DavidG - 正是我的想法。但说真的,使用File.ReadAllLines() 将 ini 文件作为列表读取是迄今为止获取所有部分的最简单方法。您只需要找到\[.*\](或简单的text.StartsWith("[") && text.Trim().EndsWith("]"))正则表达式的所有组匹配
  • 我在 @Archer..ini 文件很容易解析。我什至不会使用 Windows API。此外,如果有多个与您的代码没有相同名称的部分,Windows API 将会出错。

标签: c# ini


【解决方案1】:

最简单的方法可能是使用像 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);

而这个page 显示了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');
}

【讨论】:

  • 我无法下载 IniParser。还有其他解决方案吗?
  • @Cherylaksh 你的意思是你不能使用它,还是不能下载它?因为它有一个nuget包:nuget.org/packages/ini-parser
  • 非常感谢。我下载了包,它工作正常。! :)
猜你喜欢
  • 2016-02-04
  • 2013-04-27
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
  • 2021-10-23
  • 2013-02-17
相关资源
最近更新 更多