VB.NET比较两个文本文件并添加不足的行

时间:2013-04-21 00:57:27

标签: vb.net

我正在寻找比较两个文本文件的解决方案,并将第二个文件中的不足行添加到第一个文件中。这是一个例子。

第一个文件内容:

<category = Names>
Anton
Darell
Kate
</category>
<category = Job title>
Director
President
Manager
</category>
<category = other>
bla bla
lia lia
ohoho
</category>

第二个文件内容:

<category = Names>
Anton
Frank
Thomas
</category>
<category = Job title>
Driver
President
Manager
</category>
<category = other>
bla bla
olia olia olia
</category>

如果您注意到每个文件都有某种类别,那么我想将第二个文件中的新对象添加到第一个文件中的相同类别中,因此新文件应如下所示:

<category = Names>
Anton
Darell
Kate
Frank
Thomas
</category>
<category = Job title>
Director
President
Manager
Driver
</category>
<category = other>
bla bla
lia lia
ohoho
olia olia olia
</category>

希望这是可以解决的。

1 个答案:

答案 0 :(得分:0)

Private mResult As New List(Of String)

Public Sub MergeFiles()
    ReadFile("C:\File1.txt")
    ReadFile("C:\File2.txt")
    WriteFile("C:\Result.txt")
    mResult.Clear()
End Sub

Private Sub ReadFile(ByVal Path As String)
    Dim mSR As New System.IO.StreamReader(Path)
    Dim mItem As String = ""
    Do While Not mSR.EndOfStream
        mItem = mSR.ReadLine
        If Not mResult.Contains(mItem) Then mResult.Add(mItem)
    Loop
    mSR.Close()
    mSR.Dispose()
End Sub

Public Sub WriteFile(ByVal Path As String)
    Dim mSW As New System.IO.StreamWriter(Path)
    For Each mItem As String In mResult
        mSW.WriteLine(mItem)
    Next
    mSW.Close()
    mSW.Dispose()
End Sub