VB.Net从包含特定字符串的文本文件中返回所有行

标签 vb.net powershell text code-translation

我是编程和 Stack Overflow 的新手,如果有任何我遗漏/未提供的信息,我深表歉意,如果需要,我很乐意对这篇文章进行任何调整。

我正在尝试编写一个应用程序,该应用程序查看包含指定字符串的文本文件中的每一行,并将每个匹配的行输出到另一个文本文件。例如,如果我从以下位置搜索包含字符串 'le' 的所有行:

apple
orange
lemon
banana

apple 和 lemon 将被输出到一个单独的文件中。

我拥有的代码只会返回第一个匹配项,然后退出循环,而不寻找其他匹配项。请看下面:
  Using reader As New StreamReader(inputFilePath)
        While Not reader.EndOfStream
            Dim line As String = reader.ReadLine()
            If line.Contains(searchString) Then
                Dim outputFile As System.IO.StreamWriter
                outputFile = My.Computer.FileSystem.OpenTextFileWriter(outputFilePath, True)
                outputFile.WriteLine(line)
                outputFile.Close()
                Exit While
            End If
        End While
    End Using

为什么即使没有满足 EndOfStream 条件,代码也会退出 while 循环?

根据上面的例子,我得到的结果是:
apple

不是:
apple
lemon

我知道我没有使用附加来连续添加结果,但是如果这是问题的主要部分,那么我得到的结果肯定是:
lemon

因为 'apple' 会被找到但被第二个结果覆盖。

请任何人提供帮助,我再次很抱歉不得不打扰任何人,如果问题措辞糟糕或缺乏信息,我尤其感到抱歉,但我将永远感激任何可以提供帮助的人。这是我的第一个编程项目,我真的很想成功。

顺便说一句,该项目最初是作为一个 powershell 脚本编写的,它工作正常,所以如果任何可以帮助的人都在努力破译我的问题,那么下面的代码可以在 PowerShell 中完美运行并给出预期的结果。
$inputFile = Read-Host -Prompt 'Input File- Paste the filename, its 
extension and its path here. Eg- C:\input.log'
$outputFile = Read-Host -Prompt 'Output File- Type the filename its 
extension and its path here. Eg- C:\output.log'
$Pattern = Read-Host -Prompt 'Please paste/type the data to be searched.'

select-string -path $inputFile -Pattern $Pattern | select line | out-file 
$outputFile

再次感谢。

最佳答案

虽然 Jack Taylor 是非常正确的,即对现有代码的微小更改将解决您的直接问题,但您也可以简化代码以使您的原始错误不可能出现:

File.AppendAllLines(outputFilePath,
                    File.ReadLines(inputFilePath).
                         Where(Function(line) line.Contains(searchString)))

关于VB.Net从包含特定字符串的文本文件中返回所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43858808/

相关文章:

asp.net Session 提前过期

sql - 通过SQL运行Powershell脚本

MySQL:文本占用多少空间?

python - pygame 文本变量

mysql - 检查是否存在然后插入更新

asp.net - 如何将最后插入的 id(PK) 的值存储到主键是 VB.Net 中的 GUID 的变量中

c# - 防止在设计时调整高度控件的大小

用于在网络适配器上打开 "File and Print Sharing for Microsoft Networks"的 PowerShell 命令

function - PowerShell 将多个参数传递给类方法失败

c# - DllNotFoundException : TMPro_Plugin, 在 Linux 上使用 TextMesh Pro