Search code examples
c#file-iosystem.io.fileinfo

Exception while accessing FileInfo Class


I am trying to access all the files inside sub folders which are present inside a master folder, along with their last access times.

I am able to get all the files, the problem arises when I'm trying to get the last access times.

I receive the 'Object not set to an instance of an object' exception.

I am not able to see the anomaly in my code.

Below is the code:

public List<String> GetDirs(string Dir)
        {
            List<String> files = new List<String>();
            try
            {
                foreach (string f in Directory.GetFiles(Dir))
                {
                    files.Add(f);
                }
                foreach (string d in Directory.GetDirectories(Dir))
                {
                    files.AddRange(GetDirs(d));
                }
                int num=files.Count;
                FileInfo[] fileinfo=null;
                for (int i = 0; i < num; i++)
                {
                    fileinfo[i] = new FileInfo(files[i]);//Exception at this line of code

                }
                foreach(FileInfo xx in fileinfo)
                {
                    Response.Write(xx.LastWriteTime);
                }
              }
            catch (System.Exception excpt)
            {
                Response.Write(excpt.Message);
            }

            return files;
        }

The code is called as:

    string fullPath = @"D:\Main\Folder1";
    List<string> lst=GetDirs(fullPath);

The code is not complete at this time.

There are 3 text files inside Folder1, such as:

D:\Main\Folder1\a.txt

D:\Main\Folder1\bin\a1.txt

D:\Main\Folder1\SubFolder1\sa1.txt

I am trying to get the last access times for the above files too, but the exception doesn't permit to go further.


Solution

  • It's pretty obvious here:

    FileInfo[] fileinfo=null;   // <-- fileinfo is null
    for (int i = 0; i < num; i++)
    {
        fileinfo[i] = new FileInfo(files[i]);//Exception at this line of code
    //   ^--- fileinfo is still null!
    }
    

    you are trying to use the indexer on a null reference to set a value. I think you want:

    FileInfo[] fileinfo= new FileInfo[num];
    for (int i = 0; i < num; i++)
    {
        fileinfo[i] = new FileInfo(files[i]);//Exception at this line of code
    }
    

    or just

    FileInfo[] fileinfo = files.Select(f => new FileInfo(f)).ToArray();
    

    EDIT

    After reading your comments, it seems that you think that FileInfo[] fileinfo=null; will initialize an array of null values (which is true in some languages, but not C#). In fact, it creates an array variable that is itself a null value. To initialize an array, you use the syntax FileInfo[] fileinfo=new FileInfo[size]; which will create an array of null values (more precisely, of the default value for FileInfo, which is null since it's a reference type).