oshirowanen
oshirowanen

Reputation: 15965

Can't get my array loop right

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?

Upvotes: 0

Views: 64

Answers (3)

Thiago Ferreira
Thiago Ferreira

Reputation: 651

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++)

Upvotes: 1

Byyo
Byyo

Reputation: 2243

use < instead of <=

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

Upvotes: 4

ventiseis
ventiseis

Reputation: 3099

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++)

Upvotes: 0

Related Questions