vb.net Visual Basic 读取文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21644756/
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-17 16:43:08  来源:igfitidea点击:

Visual Basic reading text file

vb.netvisual-studio-2013

提问by nmehta_001

VB is supposed to read each line and show only the corresponding "ItemNo" however what it does is read only the last line of my code and display that, it also does not return my message if i put in an item number that does not yet exist. What would be a way of correcting this so that it chooses only the line with the corresponding "ItemNo" and have it return my message when it fails to find the number.

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

回答by Steve

It is not very clear, but supposing that you are searching for a particular string in your text file then you could write this

这不是很清楚,但假设您正在文本文件中搜索特定字符串,那么您可以编写此

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

I have used a fixed string "ItemNo", you should change it to the variable that contains the search text

我使用了固定字符串“ItemNo”,您应该将其更改为包含搜索文本的变量

Notice the usage of File.ReadLines, this methods doesn't read the whole file in memory and allows to start to search the result collection using a lambda expression

注意File.ReadLines的用法,此方法不会读取内存中的整个文件,而是允许使用 lambda 表达式开始搜索结果集合