Question

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.

Was it helpful?

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]); };

OTHER TIPS

If you look at the error message, it actually tells you exactly what is happening (you just need to be able to speak the language). "Index was out of range" means that you had N items, and you tried to take the (N + 1) item. In other words, you are trying to get something that doesn't exist, probably due to faulty logic in your program, but it also could be that you expect to have N+1 items, but don't.

Best way to catch this is to use the debugger to first find out which line you are getting the exception on. Placing a breakpoint on the first line in your ForEach (Verknüpfung.AddRange) will get you into debugging it.

To eliminate, you will need to (1) fix your input files OR (2) resolve your logic error so you are not trying to read more items than exist in the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top