Search code examples
c#fileinfo

(C#) FileInfo array out-of-bounds exception ... except it is not


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.


Solution

  • 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.