Search code examples
c#ini

Read ini key longer than 255 characters


I would like to read the key from the ini file and load it into the listbox. Everything works until the ini key exceeds 255 characters, then it gives an error

ini look like here:

[Islands]
name=Island1-6,Island2-6,Island3-6,Island4-6,stash-1,Island5-6,Island6-6,Island7-6,Island8-6,stash-1,Island9-6,Island10-6,Islandname11-6,Islandname12-6,stash-1,Islandname13-6,Islandname14-6,Islandname15-6,Islandname16-6,234234-1,2334-2,234324-3,234324-5,123123-3,end
int v = 0;
string t1Stone = new IniFile(iniFilePath).Read("name", "Islands");
Console.WriteLine(t1Stone);
string[] t1StoneValues = t1Stone.Split(',');
Loop:;
string t10 = t1StoneValues[v];

if (t10 == "end")
{
    goto Start;
}
else
{
    if (t10 == "")
    {
        goto Start;
    }
    else
    {
        listBoxWyspy.Items.Add(t10);
        v++;
        if (v < 1000)
        {
            goto Loop;
        }
        else
        {
            return;
        }
    }

}
Start:;

Solution

  • Goto should be avoided. Do this instead:

    int v = 0;
    string t1Stone = new IniFile(iniFilePath).Read("name", "Islands");
    Console.WriteLine(t1Stone);
    string[] t1StoneValues = t1Stone.Split(',');
    foreach (string s in t1StoneValues)
    {
        if (!string.IsNullOrEmpty(s) && listBoxWyspy.Items.Count < 1000 && !s.Equals("end"))
        {
           listBoxWyspy.Items.Add(s);
        }
    }
    

    This way you only work on the strings that are there.

    EDIT

    I would avoid using ini-files in this day and age, but if I had to I would organize the file thus:

    [Islands]
    islandcount = 24
    name1=Island1-6
    name2=Island2-6
    name3=Island3-6
    name4=Island4-6
    name5=stash-1
    name6=Island5-6
    name7=Island6-6
    name8=Island7-6
    name9=Island8-6
    name10=stash-1
    name11=Island9-6
    name12=Island10-6
    name13=Islandname11-6,
    name14=Islandname12-6
    name15=stash-1
    name16=Islandname13-6
    name17=Islandname14-6
    name18=Islandname15-6
    name19=Islandname16-6
    name20=234234-1
    name21=2334-2
    name22=234324-3
    name23=234324-5,
    name24=123123-3
    

    Then I would read it like this:

    var myIni = new IniFile(iniFilePath);
    int count = int.Parse(myIni.Read("islandcount", "Islands"));
    for (int i=1;i<=count;i++)
    {
        string s = myIni.Read($"name{i}", "Islands")
        if (!string.IsNullOrEmpty(s) && listBoxWyspy.Items.Count < 1000)
        {
           listBoxWyspy.Items.Add(s);
        }
    }
    

    If you look at driver ini-files that's normally how it's done.