Home > Blockchain >  Reading text from one file, to check other text file for matches
Reading text from one file, to check other text file for matches

Time:09-28

So I'm new to VB.NET, and I'm trying to read through 2 separate text files. File2 first & pulling a variable from it. I then want to take that variable, and check File1 to see if the string matches. Both files are relatively large, and I have to trim part of the string from the beginning, hence the multiple splits. So currently, this is what I have. But where I'm getting hung up is, how do I get it to check every line to see if it matches with the other file?

Public Function FileWriteTest()
Dim file1 = My.Computer.FileSystem.OpenTextFileReader(path)
Dim file2 = My.Computer.FileSystem.OpenTextFileReader(path)
Do Until file2.EndOfStream
     Dim line = file2.ReadLine()
     Dim noWhiteSpace As New String(line.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
     Dim split1 = Split(noWhiteSpace, "=")
     Dim splitStr = split1(0)
     If splitStr.Contains(HowImSplittingText) Then
     Dim parameter = Split(splitStr, "Module")
     Dim finalParameter = parameter(1)
     End If

'Here is where I'm not sure how to continue. I have trimmed the variable to where I would like to check with the other file.
'But i'm not sure how to continue from here.

CodePudding user response:

Here are a couple of cleanup notes:

  1. Get the lines of your first file by using IO.File.ReadAllLines (documentation)
  2. Get the text of the second file by using IO.File.ReadAllText (documentation)
  3. Use String.Replace (documentation) instead of Char.IsWhitespace, this is quicker and much more obvious as to what is going on
  4. Use String.Split (documentation) instead of Split (because this is 2021 not 1994).

In terms of what you would do next, you would call String.IndexOf (documentation) on the second file's text, passing your variable value, to see if it returns a value greater than -1. If it does, then you know where at in the file the value exists.

Here is an example:

Dim file1() As String = IO.File.ReadAllLines("path to file 1")
Dim file2 As String = IO.File.ReadAllText("path to file 2")
For Each line In file1
    Dim noWhiteSpace As String = line.Replace(" ", String.Empty)
    Dim split1() As String = noWhiteSpace.Split("=")
    If (splitStr.Length > 0) Then
        Dim splitStr As String = split1(0)
        If splitStr.Contains(HowImSplittingText) Then
            Dim parameter() As String = splitStr.Split("Module")
            If (parameter.Length > 0) Then
                Dim finalParameter As String = parameter(0)
                Dim index As Integer = file2.IndexOf(finalParameter)
                If (index > -1) Then
                    ' finalParameter is in file2
                End If
            End If
        End If
    End If
Next
  • Related