请帮助:我想从文件inPath读取一个块并写入另一个文件outPath。 我正在使用ReadLines方法逐行读取文件,当达到START_BLOCK时,开始写入输出文件并继续,直到找到END_BLOCK。 我通过将整个文件复制到一个变量并选择我需要的块来了解其他几种方法。我不能在变量上使用保存,因为我的文件非常大GB + 我在下面的编码复制了" START_BLOCK"在" END_BLOCK"之前,不能真正弄明白如何继续写作。请提前建议并非常感谢。
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
'-------HOW DO I CONTINUE TO WRITE UNTIL "END_BLOCK"
End If
Next line
End Using
答案 0 :(得分:0)
你可以设置一个标志来表明你在这个区块内,并用它来写出这些线,直到你找到结束标记,例如:像这样的东西(未经测试的代码!):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
Exit For
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
<强>更新强>
由于评论失控 - 这是一个版本,用于处理具有不同开始标记但具有相同结束标记的多个块(由于我在Mac上的家中未经测试):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If IsStartOfBlock(line) Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
'...
' Logic to determine if the line is the start of a block, for example:
Private Function IsStartOfBlock(line As String) As Boolean
Dim startMarkers() As String = {
"START_BLOCK", "START_BLOCK2", "START_BLOCKX"
}
Return startMarkers.Any(Function(x) line.Contains(x))
End Function
无论如何,循环将在文件末尾退出,所以最后一个块也应该没问题。