Reading text from one file, to check other text file for matches - vb.net

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.

Here are a couple of cleanup notes:
Get the lines of your first file by using IO.File.ReadAllLines (documentation)
Get the text of the second file by using IO.File.ReadAllText (documentation)
Use String.Replace (documentation) instead of Char.IsWhitespace, this is quicker and much more obvious as to what is going on
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

Text file split in blocks vb.net

I am trying to go through my text file and create a new file that will contain only the text I require. My current line looks like:
Car-1I
Colour-39
Cost-328
Dealer-28
Car-2
Colour-30
Cost-234
For each block of text I would like to read the first line, if the first line ends with an I, then read the next line, if that line contains a colour 39, then I would like to save the whole block of text to another file. If these two conditions aren't met, I dont want to save my values to the new text file.
Before anything about saving my values in classes are mentioned, these blocks of text can vary in size and values, so I dont always have a set range of values which is why i need to skip to the blank line
IO.File.WriteAllText("C:\Users\test2.txt", "") 'write to new file
Dim sKey As String
Dim sValue As Integer
For Each filterLine As String In File.ReadLines("C:\Users\test.txt")
sKey = Split(filterLine, ":")(0)
sValue = Split(filterLine, ":")(1)
If Not sValue.EndsWith("I") Then
ElseIf sValue.EndsWith("I") Then
End If
Next
Another method, using File.ReadLines to read lines of text from file. This method doesn't load all the text in memory, it reads from disc single lines of text, so it can also be useful when dealing with big files.
You could loop the IEnumerable collection it returns, but also use its GetEnumerator() method to control more directly when to move to the next line, or move more then one lines forward.
Its Enumerator.Current object returns the line of text currently read, Enumerator.MoveNext() moves to the next line.
A StringBuilder is used to store the strings when a match found. Strings are added to the StringBuilder object using its AppendLine() method.
This class is useful when dealing with strings that you need to store, compare and discard (or modify) quickly: since string are immutable, when you use String variables directly, especially in loops, you generate a whole lot of garbage that slows down any procedure quite a lot.
The blocks of text stored in the StringBuilder object are then written to a destination file using a StreamWriter with explicit encoding set to UTF-8 (writes the BOM). Its methods include asynchronous versions: WriteLine() can be replaced by awaitWriteLineAsync() to allow an async procedure.
Imports System.IO
Imports System.Text
Dim sourceFilePath = "<Path of the source file>"
Dim resultsFilePath = "<Path of the destination file>"
Dim sb As New StringBuilder()
Dim enumerator = File.ReadLines(sourceFilePath).GetEnumerator()
Using sWriter As New StreamWriter(resultsFilePath, False, Encoding.UTF8)
While enumerator.MoveNext()
If enumerator.Current.EndsWith("I") Then
sb.AppendLine(enumerator.Current)
enumerator.MoveNext()
If enumerator.Current.EndsWith("39") Then
While Not String.IsNullOrWhiteSpace(enumerator.Current)
sb.AppendLine(enumerator.Current)
enumerator.MoveNext()
End While
sWriter.WriteLine(sb.ToString())
End If
sb.Clear()
End If
End While
End Using
This will work:
Dim strFile As String = "c:\Test5\Source.txt"
Dim strOutFile As String = "c:\Test5\OutPut.txt"
Dim strOutData As String = ""
Dim SourceGroups As String() = Split(File.ReadAllText(strFile), vbCrLf + vbCrLf)
For Each sGroup As String In SourceGroups
Dim OneGroup() As String = Split(sGroup, vbCrLf)
If Strings.Right(OneGroup(0), 1) = "I" And (Strings.Right(OneGroup(1), 2) = "39") Then
If strOutData <> "" Then strOutData += (vbCrLf & vbCrLf)
strOutData += sGroup
End If
Next
File.WriteAllText(strOutFile, strOutData)
Something like this should work:
Dim base, i, c as Integer
Dim lines1$() = File.ReadLines("C:\Users\test.txt")
c = lines1.count
While i < c
if Len(RTrim(lines1(i))) Then
If Strings.Right(RTrim(lines1(i)), 1)="I" Then
base = i
i += 1
If Strings.Right(RTrim(lines1(i)), 2)="39" Then
While Len(RTrim(lines1(i))) 'skip to the next blank
i += 1
End While
' write lines1(from base to (i-1)) here
Else
While Len(RTrim(lines1(i)))
i += 1
End While
End If
Else
i += 1
End If
Else
i += 1
End If
End While

How to read from a 2-line text file and output each line to 2 variables in vb.net

Hello in my program I need for a text file containing 2 lines to be read and each line's contents to be put into their own variable. the text file is called "account.txt" and is under the directory Documents. the code i have curently that sees if it exists is this:
If File.Exists(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")) Then
MsgBox("Account found and is being loaded!")
End If
I would like in that if statement for the file to be read and each line to be read and contents to be put into their own variable. Any help is greatly appreciated!
You could either use a collection like String() or List(Of String) or read them with File.ReadLines or File.ReadAllLines and assign index 0 to variable 1 and index 1 to variable 2:
Dim path = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
If File.Exists(path) Then
Dim allLines = File.ReadAllLines(path)
Dim line1 As String = allLines(0) ' indices are zero based
Dim line2 As String = allLines(1)
End If
You can also use ElementAtOrDefault(1) instead of allLines(1) if you're not sure if the file contains two lines at all. It'l be Nothing if it contains less:
Dim line2 As String = allLines.ElementAtOrDefault(1) ' can be Nothing
If File.Exists(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")) Then
Dim accountReader As StreamReader = new StreamReader(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
Dim line1 As String = accountReader.ReadLine()
Dim line2 As String = accountReader.ReadLine()
reader.Close()
End If
This should work, have not tested it I usually work on C# so I tried to convert it to VB.Net I usually prefer to reader all lines into arrays and before assigned to it I do all necessary checks but this should get you started.
I seperated it like this since you mentioned that you want line contents into different variables.
Hope this helps you :)

VBNET Reading a specific column on a line in a text file

I have saved written a text file and it currently reads:
"first","surname","pass"
I want to read the password column so the 3rd one and define that as a variable. Its basically for a login, if pass in text file matches the entered pass (from user).
I have searched for about an hour now and no luck. Could someone guide me to a correct path.
Thanks.
Simple example of reading a small file line by line and splitting each one into fields:
' get the values from the user somehow:
Dim first As String = "James"
Dim surname As String = "Bond"
Dim pass As String = "007"
Dim validated As Boolean = False ' assume wrong until proven otherwise
' check the file:
Dim fileName As String = "c:\some folder\path\somefile.txt"
Dim lines As New List(Of String)(System.IO.File.ReadAllLines(fileName))
For Each line As String In lines
Dim values() As String = line.Split(",")
If values.Length = 3 Then
If values(0).Trim(Chr(34)) = first AndAlso
values(1).Trim(Chr(34)) = surname AndAlso
values(2).Trim(Chr(34)) = pass Then
validated = True
Exit For
End If
End If
Next
' check the result
If validated Then
MessageBox.Show("Login Successful!")
Else
MessageBox.Show("Login Failed!")
End If
If this is a CSV file, as seems to be the case, then the easiest way to read it will be with the TextFieldParser class. The MSDN already provides an excellent example for how to use it to read a CSV file, so I won't bother reproducing it here.

String Manipulation To Get An Item In The Middle Of A CSV File

I have a csv file I need to parse and get an item out of the middle of it. I have chose string manipulation to do this.
sample input file data would be..
Nick,frog,snake,1234
I can get the last entry "1234" with this code..
line.Substring(line.LastIndexOf(",") + 1)
How would I get the 3rd entry, "snake", with substrings? (what the OP means is: how can I get the third element in the comma-separated string, which happens to be "snake")
If you've stored the text of your file in myInputText, and you want to access the third item, the following will work:
resultString = Strings.Split(myInputText, ",")(2)
You can access any string in the file this way.
How would I get the 3rd entry "snake" with substrings?
The easiest way would obviously be with split:
Dim teststr As String = "Nick,frog,snake,1234"
Dim teststr2 As String = teststr.Split(","c)(2)
A simple function like this, using substring, will do the same thing:
Dim teststr3 As String = GetStr(teststr, 2)
Private Function GetStr(input As String, index As Integer) As String
input += ","
Dim counter As Integer = 0
If index <> 0 Then
Do
input = input.Substring(input.IndexOf(","c)).TrimStart(","c)
counter += 1
Loop Until counter = index
End If
GetStr = input.Substring(0, input.IndexOf(","c))
End Function

Search/Replace in VB.NET

Been following the threads for sometime as a novice (more of a newbie) but am now starting to do more.
I can read how to open a text file but am having trouble understanding the .replace functionality (I get the syntax just can't get it to work).
Scenario:
Inputfile name = test_in.txt
replace {inputfile} with c:\temp\test1.txt
I'm using test.txt as a template for a scripting tool and need to replace various values within to a new file called test_2.txt.
I've got variables defining the input and output files without a problem, I just can't catch the syntax for opening the new file and replacing.
You really have not given us that much to go on. But a common mistake in using String.Replace is that it makes a copy of the source which needs to be saved to another variable or else it will go into the bit bucket. So in your case, something like this should work.
Dim Buffer As String 'buffer
Dim inputFile As String = "C:\temp\test.txt" 'template file
Dim outputFile As String = "C:\temp\test_2.txt" 'output file
Using tr As TextReader = File.OpenText(inputFile)
Buffer = tr.ReadToEnd
End Using
Buffer = Buffer.Replace("templateString", "Hello World")
File.WriteAllText(outputFile, Buffer)
Try something like this:
Dim sValuesToReplace() As String = New String() {"Value1", "Value2", "Value3"}
Dim sText As String = IO.File.ReadAllText(inputFilePath)
For Each elem As String In sValuesToReplace
sText = sText.Replace(elem, sNewValue)
Next
IO.File.WriteAllText(sOutputFilePath, sText)
It depends if you want to replace all values with only one value, or with different values for each. If you need different values you can use a Dictionary:
Dim sValuesToReplace As New Dictionary(Of String, String)()
sValuesToReplace.Add("oldValue1", "newValue1")
sValuesToReplace.Add("oldValue2", "newValue2")
'etc
And then loop throgh it with:
For Each oldElem As String In sValuesToReplace.Keys
sText = sText.Replace(oldElem, sValuesToReplace(oldElem))
Next