简体   繁体   中英

How to read a specific line from a .txt file in VB.net

I am currently trying to create a vocabulary testing program. What I am really trying to do is get the program to generate a random number, and get the program to choose a line of text from a .txt file corresponding to the random number.

I've managed to get the random number to work, but I have no idea how to read a specific line from the .txt file.

I'm fairly proficient with My.Computer.FileSystem.ReadAllText(filename, text, etc) , but I can't seem to find any way of achieving my goal with it.

If you can help, it would be preferable if the solution could avoid StreamReader .

I would include some code, however its only a few lines long and contains only the random generator, so is pretty self explanatory.

You can use System.IO.File.ReadAllLines and the array indexer:

Private Shared rnd As New Random()

Public Shared Function GetRandomLine(path As String) As String
    Dim allLines As String() = File.ReadAllLines(path)
    Dim randomLine As String = allLines(rnd.Next(allLines.Length))
    Return randomLine
End Function

Note that Random.Next with one parameter creates a random number from 0 until allLines.Length - 1 (so exclusive upper bound ). That's correct, otherwise you'd get an IndexOutOfRangeException exception.

If you're sure the file will be reasonably small, the easiest way to read lines from a textfile is to use:

Dim lines = System.IO.File.ReadAllLines(fullFileName)

lines will be a string array, so you can access a random line from that array.

But if you're not sure that the file is small, and you don't want to risk running out of memory, a StreamReader really isn't that bad - it's designed to be easy to work with when you're reading textfiles, unlike FileStream and some of the other methods, which are a little trickier.

First you'd need to know how many lines are in the file, so you'd have to read through the file once, then a second time once you've picked a random number.

Dim numLines as Integer = 0
Using sr As New System.IO.StreamReader(fullFileName)
    Dim line As String = sr.ReadLine()
    While line IsNot Nothing
        numLines = numLines + 1
        line = sr.ReadLine()
    End While
End Using

Once you've determined how many lines there are, you can pick your random number, then repeat the process, stopping at the pre-determined line.

I have a post here that provides an alternative to ReadAll methods. There is nothing wrong with the ReadAll methods as long as the file is relatively small and memory usage is not an issue, which is normally the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM