如何读取ini文件并将其保存到列表中

How to read and save ini file to a list

我在这里搜索但没有找到解决我的问题的答案,我有一个程序可以读取报告(txt 文件)并自动填充工作簿中工作表的特定单元格。我创建了一个 ini 文件,用户将在需要时更新该文件。 我遇到的问题是我想读取 ini 文件并将某些部分的内容保存到它们自己的列表中。这是我的代码:

public class IniFile
{

    [DllImport("kernel32")]
    static extern int GetPrivateProfileString(string Section, string Key,
           string Value, StringBuilder Result, int Size, string FileName);


    [DllImport("kernel32")]
    static extern int GetPrivateProfileString(string Section, int Key,
           string Value, [MarshalAs(UnmanagedType.LPArray)] byte[] Result,
           int Size, string FileName);


    [DllImport("kernel32")]
    static extern int GetPrivateProfileString(int Section, string Key,
           string Value, [MarshalAs(UnmanagedType.LPArray)] byte[] Result,
           int Size, string FileName);

    public string path;
    public IniFile(string INIPath)
    {
        path = INIPath;
    }

    public string[] GetSectionNames()
    {
        for (int maxsize = 500; true; maxsize *= 2)
        {
            byte[] bytes = new byte[maxsize];
            int size = GetPrivateProfileString(0, "", "", bytes, maxsize, path);

            if (size < maxsize - 2)
            {
                string Selected = Encoding.ASCII.GetString(bytes, 0,
                               size - (size > 0 ? 1 : 0));
                return Selected.Split(new char[] { '[=10=]' });
            }
        }
    }

    public string[] GetEntryKeyNames(string section)
    {
        for (int maxsize = 500; true; maxsize *= 2)
        {
            byte[]  bytes   = new byte[maxsize];
            int     size        = GetPrivateProfileString(section, 0, "", bytes, maxsize, path);

            if (size < maxsize - 2)
            {
                string entries = Encoding.ASCII.GetString(bytes, 0,
                              size - (size > 0 ? 1 : 0));
                return entries.Split(new char[] { '[=10=]' });
            }
        }
    }

    public object GetEntryKeyValue(string section, string entry)
    {
        for (int maxsize = 250; true; maxsize *= 2)
        {
            StringBuilder   result  = new StringBuilder(maxsize);
            int         size        = GetPrivateProfileString(section, entry, "",
                               result, maxsize, path);
            if (size < maxsize - 1)
            {
                return result.ToString();
            }
        }
    }
}

}

这是我使用的代码:

List<string> PlacesList= new List<string>();
    List<string> PositionsList= new List<string>();

    private void btnReadini_Click(object sender, EventArgs e)
    {
        IniFile INI = new IniFile(@"C:\Races.ini");
        try
        {
            string[] SectionHeader = INI.GetSectionNames();
            if (SectionHeader != null)
            {
                foreach (string SecHead in SectionHeader)
                {
                    listBox1.Items.Add("");
                    listBox1.Items.Add("[" +SecHead+"]");

                    string[] Entry = INI.GetEntryKeyNames(SecHead);
                    if (Entry != null)
                    {
                        foreach (string EntName in Entry)
                        {
                            listBox1.Items.Add( EntName +"=" +
                                      INI.GetEntryKeyValue(SecHead, EntName));  
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            listBox1.Items.Add("Error:  " + ex);
        }
    }

这是一个示例 ini 文件

[Places]
IOM=Isle of man
UK=United Kingdom
IRE=Ireland
[Races]
IOM=7
UK=6
[Positions]
WN=Win
2nd=Second
3rd=Third
4th=Fourth

我目前可以读取 ini 文件并将其显示在我的列表框中,我现在想做的是将 [Places] 部分的名称和值保存到名为 PlacesList 的列表中,并将 Positions 的名称和值保存到一个名为 PositionsList 的列表。使用当前 class 我可以读取所有部分、键和值,但我如何才能只将我想要的数据放入列表中?

您已经接近上面的代码,但您可以只请求您需要的部分,而不是遍历所有部分(如果需要,同样可以应用于条目)。

List<string> PlacesList= new List<string>();
List<string> PositionsList= new List<string>();

public void btnReadini_Click(object sender, EventArgs e)
{
    PlacesList = ListEntries("Places");
    PositionsList = ListEntries("Positions");
}

public List<string> ListEntries(string sectionName)
{
    IniFile INI = new IniFile(@"C:\Races.ini");
    List<string> entries = null;

    string[] Entry = INI.GetEntryKeyNames(sectionName);
    if (Entry != null)
    {
        entries = new List<string>();

        foreach (string EntName in Entry)
        {
            entries.Add(EntName + "=" + INI.GetEntryKeyValue(sectionName, EntName));
        }
    }

    return entries;
}

但是,与其将数据存储在列表中,不如使用 Dictionary,然后您可以使用键来查找值。

public Dictionary<string, string> ListEntries(string sectionName)
{
    IniFile INI = new IniFile(@"C:\Races.ini");

    string[] Entry = INI.GetEntryKeyNames(sectionName);
    var entries = Entry .Where(x => !string.IsNullOrEmpty(x))
                        .ToDictionary( m => m,
                                       m => INI.GetEntryKeyValue(sectionName, m) );

    return entries;
}