vb.net 将多个文本文件合并为一个,交替行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20040258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge multiple text files into one, with alternating lines
提问by user3003346
I have managed to merge two text files together using this code
我设法使用此代码将两个文本文件合并在一起
For Each foundFile As String In
My.Computer.FileSystem.ReadAllText("path")
foundFile = foundFile
My.Computer.FileSystem.WriteAllText("path", foundFile, True)
Next
extraline = vbCrLf
My.Computer.FileSystem.WriteAllText("path", extraline, True)
My.Computer.FileSystem.WriteAllText("path", extraline, True)
For Each foundFile2 As String In
My.Computer.FileSystem.ReadAllText("path")
foundFile2 = foundFile2
My.Computer.FileSystem.WriteAllText("path", foundFile2, True)
Next
It merges them however I would like it to merge the two text files one line at a time. for example
它合并了它们,但是我希望它一次合并两个文本文件一行。例如
Textdoc1 contains
Textdoc1 包含
First Line
Third Line
Textdoc2 contains
Textdoc2 包含
Second Line
Fourth Line
I would like the output file to contain:
我希望输出文件包含:
First line
Second Line
Third Line
Fourth Line
any help is very appreciated, thanks!
非常感谢任何帮助,谢谢!
采纳答案by the_lotus
You'll have to use the ReadAllLinesinstead of ReadAllText. Here's a quick example to show you how it could work (I haven't tested this code, it's just for reference)
你将不得不使用ReadAllLines代替ReadAllText。这是一个快速示例,向您展示它是如何工作的(我尚未测试此代码,仅供参考)
Dim linesFromFile1() As String
Dim linesFromFile2() As String
Dim combinedLines As New List(Of String)
linesFromFile1 = System.IO.File.ReadAllLines("file1")
linesFromFile2 = System.IO.File.ReadAllLines("file2")
For linePos As Integer = 0 To System.Math.Max(linesFromFile1.Length, linesFromFile2.Length) - 1
If linePos < linesFromFile1.Length Then combinedLines.Add(linesFromFile1(linePos))
If linePos < linesFromFile2.Length Then combinedLines.Add(linesFromFile2(linePos))
Next
System.IO.File.WriteAllLines("file3", combinedLines.ToArray())
If you have very large file, then I suggest you look into using StreadReaderinstead. This way you can read a linewithout loading everything at once.
如果您有非常大的文件,那么我建议您考虑使用StreadReader。通过这种方式,您可以在不立即加载所有内容的情况下阅读一行。

