Streamreader-阅读下一行

时间:2018-11-09 14:21:24

标签: vb.net loops streamreader

我是VB.NET的新手,如果这是一个简单的问题,请原谅我。

我正在尝试使用OpenFileFileDialog框将文本文件的内容读取到多行文本框中。我通过执行以下操作来做到这一点:

' Set Properties of OpenFileDialog
With OpenFileDialog1
    .FileName = ""
    .Title = "Open Text File"
    .InitialDirectory = "c:\"
    .Filter = "Text files|*.txt"
    .ShowDialog()
End With

' Populate Textbox with Selected Text File Contents
txtMain.Text = File.ReadAllText(OpenFileDialog1.FileName)

然后,我想通读文件的每一行并检查前3个字符。 如果前三个字符是“ LAX”,那么我知道文件的下一行应以“ CHI”开头

所以我想阅读每一行,如果它以“ LAX”开头,我想检查文件的下一行,以确保前三个字符为“ CHI” 如果不是,我想删除任何换行符/“ LAX”行的回车符,以便将下一行带到该行的末尾。 然后,我要重复此任务,直到下一行的前3个字符为“ CHI”

基本上,这确保了与LAX相关的所有内容都在同一行上,因为当前这已拆分为文件中的多行。

这是我到目前为止所能获得的,但是我对下一步的工作感到困惑。

Using streamReader As New StreamReader(OpenFileDialog1.FileName)

    While Not streamReader.EndOfStream
        Dim line As String = streamReader.ReadLine()
        If line.StartsWith("LAX") Then
            ' Go to end of this line and remove CR or LF. Then repeat the process for the next line down until the next line down starts with "CHI"
        End If
    End While
End Using

这有意义吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

代替遍历这样的行,而是找到CHI的索引并修复之前的所有内容,然后获取之后的所有内容。这有道理吗?

' sample text I made up from your description. correct it if it's wrong
Dim text =
$"LAX{Chr(10)}ABC
D{Chr(10)}EFGH{Chr(13)}I
JCHIKLMNOP
QRST
UVW
XY
Z"
' write it to a file
File.WriteAllText("file.txt", text)
' read it back, the rest of the code would be like yours
Dim textFromFile = File.ReadAllText("file.txt")
Dim indexOfChi = textFromFile.IndexOf("CHI")
Dim result = String.Concat(textFromFile.Take(indexOfChi))
' remove line feeds
result = String.Concat(result.Replace(Chr(10), String.Empty))
' remove carriage returns too (these can be done in one line with vbCrLf or Environment.NewLine)
result = String.Concat(result.Replace(Chr(13), String.Empty))
result &= Environment.NewLine & String.Concat(textFromFile.Skip(indexOfChi))
MessageBox.Show(result)

诚然,这不是最有效的代码,但它似乎有效。

答案 1 :(得分:0)

我的输入(Test.txt的内容)

something1
LAX something2
CHI something3
LAX something4
something5
something6
CHI something7
something8

我的输出(TextBox1的内容)

something1
LAX something2
CHI something3
LAX something4 something5 something6
CHI something7
something8

代码

Dim line As String = ""
Using streamReader As New StreamReader(OpenFileDialog1.FileName)
     Dim previousLine As String = ""
     While Not streamReader.EndOfStream
         Dim nextLine = streamReader.ReadLine()
         If nextLine.StartsWith("LAX") Or nextLine.StartsWith("CHI") Then
             line &= Environment.NewLine & nextLine
             previousLine = nextLine
         ElseIf previousLine.StartsWith("LAX") Then
             line &= " " & nextLine
         Else
             ine &= Environment.NewLine & nextLine
         End If
     End While
End Using
TextBox1.Text = line