我是编程和堆栈溢出的新手,所以如果有任何我遗漏/没有提供的信息,我很抱歉,如果需要的话,我很乐意对这篇文章进行任何调整。
我正在尝试编写一个应用程序,它查看包含指定字符串的文本文件中的每一行,并将每个匹配的行输出到另一个文本文件。例如,如果我从以下位置搜索包含字符串'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
我知道我没有使用append来连续添加结果,但是如果这是问题的主要部分,那么我得到的结果肯定是:
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
再次感谢。
发布于 2017-05-09 07:49:46
这是由于循环中的Exit While
代码行造成的。这将在第一次匹配后退出整个循环。如果您只删除这一行,那么它应该可以工作。
而且,这有点矛盾,但最好是打开输出文件一次,然后在循环之后关闭它,而不是在每次迭代时打开并关闭它。(如果没有匹配项,效率会较低,但如果有多个匹配项,则效率会高得多。)下面这样的代码应该可以解决这个问题。
Using reader As New StreamReader(inputFilePath), writer As New StreamWriter(outputFilePath)
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
If line.Contains(searchString) Then
writer.WriteLine(line)
End If
End While
End Using
注意:我做了很多编程,但我以前从未使用过VB.net,上面的代码也是未经测试的,所以请对此建议持保留态度!
发布于 2017-05-09 08:03:02
虽然Jack Taylor非常正确地认为,对现有代码进行小的更改就可以解决当前的问题,但您也可以以这样一种方式简化代码,使您的原始错误变得不可能:
File.AppendAllLines(outputFilePath,
File.ReadLines(inputFilePath).
Where(Function(line) line.Contains(searchString)))
https://stackoverflow.com/questions/43858808
复制相似问题