比较两个文本文件时如何显示不匹配的行?

时间:2014-05-27 06:31:12

标签: vb.net

我是VB.Net的新手。我已经实现了脚本来比较两个检查值或数据是否彼此不同的文本文件。唯一的问题是它只显示一行而不是两行

以下是文字A和C中的数据:

文字A: Orange,Apple,Mango,Strawberry,Banana

文字B: Orange, Apple, Mango, Blueberry, Grapes

这是我的剧本

Sub Main()
    Const ForReading = 1
    Dim objFile1, objFile2, objFile3
    Dim objFSO = CreateObject("Scripting.FileSystemObject")
    objFile1 = objFSO.OpenTextFile("C:\Scripts\A.txt", ForReading) 'Current.txt represents Text from AWS network
    Dim strAddresses, strCurrent, strNoAddress
    strAddresses = objFile1.ReadAll
    objFile1.Close()

    objFile2 = objFSO.OpenTextFile("C:\Scripts\C.txt", ForReading) 'Current.txt represents Text from Shell network

    Do Until objFile2.AtEndOfStream
        strCurrent = objFile2.ReadLine
        If InStr(strAddresses, strCurrent) = 0 Then
            strNoAddress = strCurrent & vbCrLf

        End If
    Loop

    objFile2.Close()

    objFile3 = objFSO.CreateTextFile("C:\Scripts\Differences.txt")

    objFile3.WriteLine(strNoAddress)
    objFile3.Close()
End Sub

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为每当strNoAddress条件为if时,您都会覆盖true

strNoAddress = strCurrent & vbCrLf

因此,当您点击Blueberry时,strNoAddress变为Blueberry\n 当您点击Grapes时,strNoAddress变为Grapes\n而不是Blueberry\nGrapes\n

您想要连接字符串:

strNoAddress &= strCurrent & vbCrLf

更多"最新"没有VB6的遗留/剩余功能的代码版本可能如下所示:

Dim addresses = File.ReadAllLines("C:\Scripts\A.txt")

Dim noAdress = String.Empty
Using reader = new StreamReader("C:\Scripts\B.txt")
    Do Until reader.EndOfStream
        Dim current = reader.ReadLine
        If Not addresses.Contains(current) Then
            noAdress &= current & Environment.NewLine
        End If
    Loop
End Using
...

或者,为了使它更简单(对于小文件而言,并且没有训练换行符):

Dim fileA = File.ReadAllLines("C:\Scripts\A.txt")
Dim fileB = File.ReadAllLines("C:\Scripts\B.txt")
Dim noAdress = String.Join(Environment.NewLine, fileB.Where(Function(b) Not fileA.Contains(b)))