Tags:
tech news
How To Read a TextFile With Stream Reader VS System.IO.File.ReadAll In VB.NET
In this simple snipped, I will demonstrate how to read a file by two different methods, and I will show you how to return a specific line by number from a file. The code is self explanatory as are the comments in-line also explanatory so lets dive in:
line = sr.ReadLine() 'Utilising the string we created earlier, but not entirely needed as you can work direct with sr.ReadLine()
Console.WriteLine(line)
'The reality here is, that unless you know something about the line you are trying to receive, you can't really select a line of
choice. But you could do something like:
If line.Contains("Test") Then 'Assume the line you want has the word Test in it. If so, the statement will enter on the basis its
true.
'This is our line, so do your work here
End If
Loop Until line Is Nothing 'When the line is nothing, it will stop looping
sr.Close() 'Close the reader
Catch exe As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(exe.Message)
End Try
End Sub
End Class
Now lets say for arguments sake, you know which line you want to read but you don’t know how to do it? The following subroutine will demonstrate how to accomplish this with a button click event to pass the file path to a function along with the line you want to retrieve from the reader function:
Private Sub cmdRead_Click(sender As Object, e As EventArgs) Handles cmdRead.Click 'Readline calls the function name, epath equals the path you want to pass to the function, and iLine is the line you want to read from the file. ReadLine(ePath:="C:\Users\Admin\Desktop\A.txt", iLine:=4) End Sub
Now we will explain what the above code is doing inside the function below, which was initiated by the button click event above. In the above event, we named our button ‘cmdRead’:
'Send the path to ePath, and the line you want to iLine, and address the function by name: ReadLine Private Function ReadLine(ByVal ePath As String, ByVal iLine As Integer) As String If File.Exists(ePath) = True Then 'Check if the path exists before executing, or we will get errors. Dim ourLineStr As String = File.ReadAllLines(ePath).ElementAt(iLine).ToString 'Above we have used System.IO instead of a stream reader, because its easier to get the values we want from a specific line. We do this by making use of the ElementAt<> point. Something to note at this point is, if we want line 4, we need to send it an integer of 3 from our button event to get line 4. ElementAt<> is always one point behind. Why? Because ReadAllLines() returns each line from a array of strings, and arrays always start a 0. Console.WriteLine(ourLineStr) Return ourLineStr End If End Function