0

I'm getting an Index was outside the bounds of the array.

string[] paths = { 
                        "\\\\server\\c$\\folder\\subfolder\\user1\\300\\1\\abc.docx",
                        "\\\\server\\c$\\folder\\subfolder\\user2\\400\\1\\xyz.docx",
                    };

FileInfo[] f = new FileInfo[paths.Length];

for (int i = 0; i <= paths.Length; i++)
{
    f[i] = new FileInfo(paths[i]);
    Console.WriteLine(f[i].Length);
}

I can't seem to figure out why, any ideas?

2
  • 7
    use < instead of <= Commented Feb 26, 2016 at 14:49
  • Also, if you don't need the index i, you can actually use foreach instead of for to avoid such error. Consider also of using List instead of Array for your FileInfo Commented Feb 26, 2016 at 15:01

3 Answers 3

4

use < instead of <=

for (int i = 0; i < paths.Length; i++)
{
    f[i] = new FileInfo(paths[i]);
    Console.WriteLine(f[i].Length);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Arrays start counting itens from 0. So, if you have an array with length 2, your objects will be in position [0] and [1]. If you try to access the position [2], you'll get the Index was outside the bounds of the array exception, because index 2 doesn't exist in this array.

In your for loop, you're using <= paths.Length. Your paths length is 2. 2 is less or equals 2, so your code will be executed like this

f[2] = new FileInfo(paths[2]) //Position 2 doesn't exist

To solve this, just change from:

for (int i = 0; i <= paths.Length; i++)

To:

for (int i = 0; i < paths.Length; i++)

Comments

0

You have two items in your array

paths[0], paths[1]

Your looping over three items

paths[0], paths[1], paths[2]

To correct this, change

for (int i = 0; i <= paths.Length; i++)

to

for (int i = 0; i < paths.Length; i++)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.