阅读.text文件

时间:2011-07-30 17:02:38

标签: vb.net

我使用以下代码从.txt文件中读取文本。但我不知道该怎么做 在文件中执行搜索以及如何根据搜索读取文本文件中的特定行。

Dim vrDisplay = My.Computer.FileSystem.ReadAllText(CurDir() & "\keys.txt")
    MsgBox(vrDisplay)

例如,

如果我想阅读包含单词“Start”的行,该怎么做

感谢。

2 个答案:

答案 0 :(得分:3)

为了效率,而不是阅读所有文本,

  • 打开相关文件的FileStream。
  • 创建StreamReader。
  • 循环,调用ReadLine直到找到文件末尾,或者字符串包含“Start”。

编辑:即使您需要将整个文件保留在内存中,您仍然可以使用MemoryStream()执行上述操作。

答案 1 :(得分:2)

从您的帖子中判断它是否是最佳解决方案并不容易,但一种解决方案是使用regular expressions查找包含单词Start的所有行:

^.*\bStart\b.*$

匹配包含完整单词Start的整行。它拒绝Start作为单词的一部分,例如Starting将不会匹配(这就是\b单词边界锚定的内容)。

在VB.NET中使用它:

Dim RegexObj As New Regex(
    "^      # Start of line" & chr(10) & _
    ".*     # Any number of characters (anything except newlines)" & chr(10) & _
    "\b     # Word boundary" & chr(10) & _
    "Start  # ""Start""" & chr(10) & _
    "\b     # Word boundary" & chr(10) & _
    ".*     # Any number of characters (anything except newlines)" & chr(10) & _
    "$      # End of line", 
    RegexOptions.Multiline Or RegexOptions.IgnorePatternWhitespace)
AllMatchResults = RegexObj.Matches(vrDisplay)
If AllMatchResults.Count > 0 Then
    ' Access individual matches using AllMatchResults.Item[]
Else
    ' Match attempt failed
End If