This seems so easy, but I'm pulling my hair out because I can't figure it out. Maybe some fresh eyes will be able to spot my glaringly simple mistake that I just can't find.

I want to read a text file in, line by line, sort the lines, and write back to the same text file. But I'm having problems assigning the line that is read from the file to an element of the array. Here's my code:

VB Code:
  1. If File.Exists(outputpath & dir.ToLower & ".txt") Then
  2.                 'append to file
  3.                 sr = File.AppendText(outputpath & dir.ToLower & ".txt")
  4.                 sr.WriteLine(filename & ";" & filedate & ";" & dir & ";" & filesize)
  5.                 sr.Close()
  6.                 ' Sort file by filename
  7.                 Dim sortfile() As String
  8.                 Dim inputfile As New StreamReader(outputpath & dir.ToLower & ".txt")
  9.                 Dim inputstring As String
  10.                 inputstring = inputfile.ReadLine()
  11.                 Dim i As Integer = 0
  12.                 While (inputstring <> Nothing)
  13.                     Try
  14.                         sortfile(i) = inputstring
  15.                     Catch ex As Exception
  16.                         MessageBox.Show(ex.Message, "Caught Exception")
  17.                     End Try
  18.  
  19.                     i = i + 1
  20.                     inputstring = inputfile.ReadLine()
  21.                 End While
  22.                 inputfile.Close()
  23.                 System.Array.Sort(sortfile)
  24.                 Dim outputfile As New StreamWriter(outputpath & dir.ToLower & ".txt")
  25.                 Dim j As Integer = 0
  26.                 While j < sortfile.Length
  27.                     outputfile.WriteLine(sortfile(j))
  28.                     j = j + 1
  29.                 End While
  30.                 outputfile.Close()
  31.             Else
  32.                 'create new file
  33.                 sr = File.CreateText(outputpath & dir.ToLower & ".txt")
  34.                 sr.WriteLine(filename & ";" & filedate & ";" & dir & ";" & filesize)
  35.                 sr.Close()

I keep getting the exception
Object reference not set to an instance of an object
when reading the file in, right at the line:
VB Code:
  1. sortfile(i) = inputstring

Is this not allowed?