Search code examples
c#listcollectionsclickfile.readalllines

C#: Index was out of range, must be non-negative and less than the size of the collection


I did the following programming. Running the application shows an error message: Index was out of range. Must be non-negative and less than the size of the collection.

EDIT:

public void SetShortcuts()
    {
        List<string> Verknüpfung = new List<string>();
        int i = 0;
        int j = 0;

        try
        {
            foreach (string Datei in Directory.GetFiles(PfadShortcuts, "*.txt"))
            {
                Verknüpfung.AddRange(File.ReadAllLines(Datei, Encoding.UTF8));

                Image ShortcutIcon = new Image();
                ShortcutIcon.Source = new BitmapImage(new Uri(@"Fugue Icons\document.png", UriKind.Relative));
                ShortcutIcon.Height = 16;
                ShortcutIcon.Width = 16;
                ShortcutIcon.Stretch = Stretch.None;

                MenuItem Shortcut = new MenuItem();
                Shortcut.Icon = ShortcutIcon;
                Shortcut.Header = Verknüpfung[0 + i];
                Shortcut.Padding = new Thickness(5);
                Shortcut.Click += delegate { Process.Start(Verknüpfung[0 + j]); };

                Shortcuts.Items.Add(Shortcut);
                i += 2;
                j++;
            }
        }
        catch
        {
            Fehlermeldung_Main_Shortcuts();
        }
    }

Could you please help me? Thanks in advance.

Kind regards.


Solution

  • Look at lines:

    Verknüpfung.AddRange(File.ReadAllLines(Datei, Encoding.UTF8));
    

    and

    Shortcut.Click += delegate { Process.Start(Verknüpfung[1 + i]); };
    

    Verknüpfung[1 + i] is one higher than then number of items in the list.

    i seems to be incrementing faster than the list is populated.

    Try changing

    Shortcut.Click += delegate { Process.Start(Verknüpfung[1 + i]); };
    

    to

    Shortcut.Click += delegate { Process.Start(Verknüpfung[0 + i]); };