2

I am receiving a "Object reference not set to an instance of an object." Error when trying to populate the fileDetails array. I am new to vb.net and I am lost.

Public Sub FindAllOrphanFiles(ByVal targetDirectory As String)
    Dim fileEntries As String() = Directory.GetFiles(targetDirectory)

    ' Process the list of files found in the directory. 
    Dim files As String
    Dim iCount As Integer = 0
    Dim fileDetails As String(,)
    For Each files In fileEntries
        Dim fileIcon As String
        Dim thisFile As New IO.FileInfo(files)

        Dim fileName As String = thisFile.Name
        Dim fileSize As String = thisFile.Length
        Dim fileDateModified As String = thisFile.LastWriteTime
        Dim fileExtension As String = Path.GetExtension(fileName)
        Dim fileShortPath As String = Replace(Replace(files, uploadFolderPath, ""), fileName, "")
        Dim fileFullPath As String = files
        If fileExtension = ".pdf" Then
            fileIcon = "acrobat"
        Else
            fileIcon = "paint"
        End If

        ' Write to Array
        fileDetails(iCount, 0) = fileIcon
        fileDetails(iCount, 1) = fileName
        fileDetails(iCount, 2) = fileShortPath
        fileDetails(iCount, 3) = fileDateModified
        fileDetails(iCount, 4) = fileSize
        fileDetails(iCount, 5) = fileFullPath

        iCount += 1
    Next files
    Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)

    ' Recurse into subdirectories of this directory. 
    Dim subdirectory As String
    For Each subdirectory In subdirectoryEntries
        FindAllOrphanFiles(subdirectory)
    Next subdirectory

End Sub 'FindAllOrphanFiles

Any help would be greatly appreciated.

neojakey
  • 1,543
  • 4
  • 23
  • 33
  • your array is declared but not initialized to any size. Since it is difficult to know ahead of time how big to make them, consider a collection type. possible duplicate of [What is a NullReferenceException](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) and how do I fix it? – Ňɏssa Pøngjǣrdenlarp Aug 01 '14 at 18:19
  • 1
    You should really concider using a List(Of ) and store the information properly inside a class. This will reduce a lot of your problem and add redability to your code. – the_lotus Aug 01 '14 at 18:47

1 Answers1

2

Your array is not initialized. If you know the size at some point before your loop, you should initialize it using REDIM:

Dim fileDetails As String(,)
redim fileDetails(fileEntries.Count -1,5)
For Each files In fileEntries
  ....

If you don't know it ahead of time, use Redim Preserve inside you loop:

Dim fileDetails As String(,)
Dim I as int32 = -1
For Each files In fileEntries
    I += 1
    redim preserve fileDetails(i,5)
    ....
Steve
  • 5,465
  • 1
  • 16
  • 32