tags:

views:

349

answers:

3

Code:

DirectoryInfo[] d2 = new DirectoryInfo[400];
d2 = moreDirect.GetDirectories();
//Declaring FileInfo array
FileInfo[] f = new FileInfo[300];
f = d2[z].GetFiles();
if (d2[z].Exists)

{  
    if (f[y] != null)
    {
     ...
     //FileInfo does it stuff and somewhere it does ++y depending on the situation blahblahblah

         if (f[y] == null) <-------- Right here is where it does it!  And y only equals 1 here.  I checked.
         {
              y = 0;
              fileTime = false;
              break;
         }

So, does anyone know what is going wrong? I have racked my brain. I have googled, I have stack overflow searched. It has to be something silly. I have no idea.

+2  A: 

There must not be an element at index 1 in the array, to be safe you should iterate over the array using foreach or for (int i=0;i<array.length;i++) never try to access an array element unless you have programatically confirmed it's existence.

Paul Creasey
+6  A: 
FileInfo[] f = new FileInfo[300];
f = d2[z].GetFiles();

You are reassigning another array to your f variable. Having just one element in the array returned by d2[z].GetFiles();, may cause your problem (y == 0 in the first if condition and y == 1 in the second).

Li0liQ
+7  A: 

GetFiles() returns a new array. It doesn't matter that you declared f to be an array of size 300 just before, when GetFiles returns it reassigns f with the new array and the old size 300 one is lost.

FileInfo[] f = new FileInfo[300];  //<-- Creates a array of size 300.
f = d2[z].GetFiles();              //<-- replaces f with a new array. This array will contain just enough space for the number of files found.

You actually don't need to create the array at all, you can just do this.

FileIndo[] f = d2[z].GetFiles();

When you need to access it you should check the arrays length first or use a for/foreach loop to iterate over each item in the array.

Simon P Stevens