vb.net 如何从VB中的文本文件中读取特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15708368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:47:08  来源:igfitidea点击:

How to read a specific line from a text file in VB

vb.net

提问by scapegoat17

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.

我正在创建一个应该将文本写入文本文件的程序,并且应该能够从 VB 中的文本文件中读取特定行(因此,如果我需要读取特定名称,我可以选择第 5 行,它会显示在文本框)。我能够从文本文件中读取文本,但我不知道如何控制特定行。

Here is my code:

这是我的代码:

Public Class Form1

    Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
         Dim writer As New System.IO.StreamWriter("/text.txt", True)
         writer.WriteLine(txtFirstName.Text)
         writer.WriteLine(txtLastName.Text)
         writer.WriteLine("-------------------------------------")
         writer.Close()
    End Sub

     Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
        Dim reader As New System.IO.StreamReader("/text.txt")
        Dim FirstName, LastName As String
        FirstName = reader.ReadLine()
        LastName = reader.ReadLine()
        reader.Close()
        txtFirstName.Text = FirstName
        txtLastName.Text = LastName
    End Sub

    Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
        txtFirstName.Clear()
        txtLastName.Clear()
    End Sub
End Class

Any help would be appreciated. Thanks!

任何帮助,将不胜感激。谢谢!

回答by stakx - no longer contributing

You will have to read all lines up to the one you're interested in. For example:

您必须阅读所有行,直到您感兴趣的行为止。例如:

Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
    Using file As New StreamReader(filePath)
        ' Skip all preceding lines: '
        For i As Integer = 1 To lineNumber - 1
            If file.ReadLine() Is Nothing Then
                Throw New ArgumentOutOfRangeException("lineNumber")
            End If
        Next
        ' Attempt to read the line you're interested in: '
        Dim line As String = file.ReadLine()
        If line Is Nothing Then
            Throw New ArgumentOutOfRangeException("lineNumber")
        End If
        ' Succeded!
        Return line 
    End Using
End Function

This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.

这是因为文本行是可变长度的记录,并且无法猜测特定行开始的确切文件偏移量 - 不是没有索引。

If you frequently need to load a specific line, you have some more options:

如果您经常需要加载特定行,您还有更多选择:

  • Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String()array which you can access by line number directly.

  • Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer)as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seekright to the beginning of a specific line without having to keep the whole file in memory.

  • 将完整的文本文件加载到内存中,例如使用File.ReadAllLines("Foobar.txt"). 这将返回一个String()数组,您可以直接通过行号访问该数组。

  • 手动创建行号索引。也就是逐行处理一个文本文件,边走边填a Dictionary(Of Integer, Integer)。键是行号,值是文件偏移量。这使您可以.Seek直接到达特定行的开头,而不必将整个文件保存在内存中。

回答by Hanlet Esca?o

Try this:

尝试这个:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim reader As New System.IO.StreamReader("C:\text.txt")
    Dim allLines As List(Of String) = New List(Of String)
    Do While Not reader.EndOfStream
        allLines.Add(reader.ReadLine())
    Loop
    reader.Close()
    txtFirstName.Text = ReadLine(5, allLines)
    txtLastName.Text = ReadLine(6, allLines)

End Sub

Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
    Return lines(lineNumber - 1)
End Function

If you had a file with this:

如果你有这样的文件:

Line 1
Line 2
Line 3
Line 4
My Name
My LastName

your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.

您的姓名文本框将包含“我的名字”,而您的姓氏文本框将包含“我的姓氏”。

回答by Ali Malik

This is very simple, try this:

这很简单,试试这个:

Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3

myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString

回答by Randy J. Tomlinson

i tried this and it works fine. using VB Express content inside test.txt:

我试过了,效果很好。在 test.txt 中使用 VB Express 内容:

line1
line2
1
John

then in the form i add

然后在我添加的表格中

textbox1
textbox2
label1
label2

and a button.

和一个button

code inside the button:

按钮内的代码:

     Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
        Dim myLine As String
        Dim lineNumber0 As Integer
        lineNumber0 = 0
        Dim lineNumber1 As Integer
        lineNumber1 = 1
        Dim lineNumber2 As Integer
        lineNumber2 = 2
        Dim lineNumber3 As Integer
        lineNumber3 = 3

        TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
        TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
        Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
        Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString

    End Sub

回答by Manuel Alves

Yet another option

又一个选择

    Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
    Dim nthLine As String = Nothing
    Dim n As Integer
    Try
        Using sr As StreamReader = New StreamReader(fileAndPath)
            n = 0
            Do While (sr.Peek() >= 0) And (n < lineNumber)
                sr.ReadLine()
                n += 1
            Loop
            If sr.Peek() >= 0 Then
                nthLine = sr.ReadLine()
            End If
        End Using
    Catch ex As Exception
        Throw
    End Try
    Return nthLine
End Function