8

After trying a few error checking methods I have come to the conclusion I need help solving this problem.

How am I not catch this "index out of range" error. What can I do to avoid this problem in the future for good practice?

    public void loadFromFile()
    {
        OpenFileDialog oFile = new OpenFileDialog();
        oFile.Title = "Open text file";
        oFile.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
        oFile.FilterIndex = 1;
        oFile.InitialDirectory = Application.StartupPath;
        oFile.AddExtension = true;
        oFile.CheckFileExists = true;
        oFile.CheckPathExists = true;

        // Open and clean Duplicates
        String[] lines;
        List<string> temp = new List<string>();
        List<string> newlist = new List<string>();

        if(oFile.ShowDialog() == DialogResult.OK)
        {
            // Dummy file has 6 lines of text. Filename:DuplicatFile.txt
            // 3 duplicate lines and 3 not.
            lines = File.ReadAllLines(oFile.FileName, System.Text.Encoding.UTF8);

            // Copy array to temporary array
            for (int index=0; index < lines.Length; index++)
            {
                // System.ArgumentOutOfRangeException was unhandled
                // Index was out of range. Must be non-negative and less than the size of the collection.
                if (lines[index].Length >= 0)
                {
                    temp[index] = lines[index];
                }
            }
            // Check for duplicates. If duplicate ignore if non-duplicate add to list.
            foreach (string line in temp)
            {
                if (!newlist.Contains(line))
                {
                    newlist.Add(line);
                }
            }
            // Clear listbox and add new list to listbox.
            lstBox.Items.Clear();
            foreach (string strNewLine in newlist)
            {
                lstBox.Items.Add(strNewLine);
            }
        }
    }

4 Answers 4

9
List<string> temp = new List<string>();
...
temp[index] = lines[index];

temp starts out with 0 size. Any index is out of range.

You can fix this by using temp.Add, to make the list grow dynamically:

temp.Add(lines[index]);
Sign up to request clarification or add additional context in comments.

1 Comment

I should have known! Well done! I totally over looked that! Thanks for the advice I will try to stick to that method.
2

Mud has the correct answer for the ArgumentOutOfRangeException. You can simplify all the code in your if statement with Linq to be the following:

lines = File.ReadAllLines(oFile.FileName, System.Text.Encoding.UTF8);    
lstBox.Items.AddRange(lines.Distinct().ToArray());

5 Comments

but if I was to do that how would it get rid of the duplicates?
The call to Distinct() will eliminate any duplicates lines. Take a look at the documentation for more information msdn.microsoft.com/en-us/library/bb348436.aspx.
I like the idea of this, but it gives me a error. "cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'object[]'"
Updated the answer to change the IEnumerable to an array. It should work now.
That is still really short! Works pretty well! Thanks for helping with this.
1

The problem isn't that the "lines" index is out of range - it's that the "temp" index is out of range... you have created a new List called "temp" but there is nothing in it.. it's length is 0!

Instead of copying from one index to another, you should use the .Add method:

temp.Add(lines[index])

of course... there better ways to duplicate an array, but this is closest to what you present above and answers your question directly.

Comments

1

You get that error, because there is no elements at that index in list temp. (temp is empty). You can fill it with temp.Add(value).

Another way to create temp list is to use temp = newlist.ToList().

I would suggest to use LINQ: You can use

lstBox.Items.Clear();
foreach (var line in lines.Distinct())
    lstBox.Items.Add(line);

instead of all this code:

// Copy array to temporary array
for (int index=0; index < lines.Length; index++)
{
    // System.ArgumentOutOfRangeException was unhandled
    // Index was out of range. Must be non-negative and less than the size of the collection.
    if (lines[index].Length >= 0)
    {
        temp[index] = lines[index];
    }
 }
 // Check for duplicates. If duplicate ignore if non-duplicate add to list.
 foreach (string line in temp)
 {
   if (!newlist.Contains(line))
   {
       newlist.Add(line);
   }
 }
 lstBox.Items.Clear();
 foreach (string strNewLine in newlist)
 {
    lstBox.Items.Add(strNewLine);
 }

to simple:

2 Comments

I never knew about that one. Linq I dont use that often. I will try to use it more.
Linq is great thing, have a look at it. Life becomes more bright))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.