VB应该读取每一行并仅显示相应的" ItemNo"但它所做的只是读取我的代码的最后一行并显示它,如果我输入一个尚不存在的项目编号,它也不会返回我的消息。什么是纠正这个的方法,以便它只选择具有相应的" ItemNo"当它找不到号码时让它返回我的信息。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckNum.Click
Dim File As String = "K:\Access to Computing Folder\Monday\Nicholas Kakou\Assignments\Assignment 2\MicroNut Software Ltd\MicroNut Software Ltd\Data Files\StockFile.dat"
Dim TextLine As String = ""
If System.IO.File.Exists(File) = True Then
Dim objReader As New System.IO.StreamReader(File)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine() & vbNewLine
Loop
MsgBox(TextLine)
Else
MsgBox("File Does Not Exist", MsgBoxStyle.OkOnly)
End If
End Sub
答案 0 :(得分:2)
目前还不是很清楚,但假设您正在文本文件中搜索特定字符串,那么您可以写这个
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckNum.Click
Dim FileName As String = ".........."
If System.IO.File.Exists(FileName) = True Then
Dim result = File.ReadLines(FileName)
Dim line = result.Where(Function (x) x.Contains("ItemNo")).FirstOrDefault()
If line Is Nothing Then
MsgBox.Show("Not Found")
Else
MsgBox.Show(line)
End If
Else
MsgBox.Show("File Not Found")
End If
End Sub
我使用了固定字符串“ItemNo”,您应该将其更改为包含搜索文本的变量
注意File.ReadLines的用法,此方法不读取内存中的整个文件,并允许使用lambda表达式开始搜索结果集合