【问题标题】:Searching text in a .txt file using visual basic使用 Visual Basic 在 .txt 文件中搜索文本
【发布时间】:2019-02-13 14:59:57
【问题描述】:

我正在制作一个项目,该项目根据用户在文本框中提供的一些单词来搜索文档以在文本文件中进行搜索。 我在基本的 Windows 窗体应用程序上使用 Visual Studio 2013,并希望根据文本框中的单词打开文件组件。 文本必须从所需的点打开。

【问题讨论】:

  • 你的问题是什么?
  • 我有一个带有文本框的表单,它从用户那里获取文本并在我的计算机的 txt 文件中搜索这些文本。
  • 如果您提供您为解决问题而编写的代码,我们可以帮助您解决您遇到的任何类型的错误,但无需您付出任何努力,它只是一个 gimme teh codez 一种问题。这里不太受欢迎。
  • 我刚开始学习这门语言,不太擅长。如果你能帮助我,它将非常有用。@Steve

标签: vb.net winforms


【解决方案1】:

如果我理解了您的问题,您想根据用户输入在 txt 文件中找到一个关键字,以便做某事。这是一个小 sn-p 给你一些例子和一个好的起点。

片段

Dim reader As StreamReader
Dim txtInput as String = "YOUR_TXT_FILE_PATH"

'The reader opens the txt input specified with the file path
reader = My.Computer.FileSystem.OpenTextFileReader(txtInput)

'Create a string from the txt file
Dim txtString as String = reader.ReadLine.TrimStart
Dim wordFound as String 

'Use Regex inside a Try/Catch statement in order to catch any possible exception.
'If Regex.Match doesn't find your TextBox1.Text inside the string it will throw an exception
Try
    'Use Regex to find your word or your expression inside the string created before
    For Each data As Match In Regex.Matches(txtString, TextBox1.Text)
        wordFound = txtString.Substring(data.index, TextBox1.Text.Lenght())
        'Do your stuff with your word found in the txt...
    Next
Catch ex As Exception
    Err.Clear()
Finally
    'Close the reader before the Try/Catch statement
    reader.Close()
End Try

我建议您先阅读有关Regex.Match 的文档,如果您有任何疑问,请随时提问。

欢迎来到 StackOverflow!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多