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:
If File.Exists(outputpath & dir.ToLower & ".txt") Then 'append to file sr = File.AppendText(outputpath & dir.ToLower & ".txt") sr.WriteLine(filename & ";" & filedate & ";" & dir & ";" & filesize) sr.Close() ' Sort file by filename Dim sortfile() As String Dim inputfile As New StreamReader(outputpath & dir.ToLower & ".txt") Dim inputstring As String inputstring = inputfile.ReadLine() Dim i As Integer = 0 While (inputstring <> Nothing) Try sortfile(i) = inputstring Catch ex As Exception MessageBox.Show(ex.Message, "Caught Exception") End Try i = i + 1 inputstring = inputfile.ReadLine() End While inputfile.Close() System.Array.Sort(sortfile) Dim outputfile As New StreamWriter(outputpath & dir.ToLower & ".txt") Dim j As Integer = 0 While j < sortfile.Length outputfile.WriteLine(sortfile(j)) j = j + 1 End While outputfile.Close() Else 'create new file sr = File.CreateText(outputpath & dir.ToLower & ".txt") sr.WriteLine(filename & ";" & filedate & ";" & dir & ";" & filesize) sr.Close()
I keep getting the exception
when reading the file in, right at the line:Object reference not set to an instance of an object
VB Code:
sortfile(i) = inputstring
Is this not allowed?




Reply With Quote