Read specific data from notepad - vb.net

I have a notepad with some unscrambled data as shown below and would like to read data from that text file and populate data to individual textboxes.
This is how my input looks likes:
========================================================
Modified Date : 5/20/2019 8:45:56 AM Modified by : 123
ID : 18677544
OLD Values:
First Name Last Name Middle Initial
-------------- -------------- -----------------
John Humpty
NEW Values:
First Name Last Name Middle Initial
-------------- -------------- -----------------
George Louis
========================================================
This is my code
Dim path As String = "C:\Users\XXX\Desktop\123.txt"
Dim searchTarget = "Modified Date"
For Each line In File.ReadAllLines(path)
If line.Contains(searchTarget) Then ' found it!
Dim toBeSearched As String = "Modified Date : "
Dim code As String = line.Substring(line.IndexOf(toBeSearched) + toBeSearched.Length)
txtModifiedDate.Text = code// Here I'm getting Modified By value also but I need only the Modified Date in this textbox similarly for others
Exit For ' then stop
End If
Next line
As per preciousbetine getting overload exception error
Updated :

If the sample text file you gave is how it always looks like, then this should work.
I hardcoded most of the values but for the text file above, the below code works:
Sub GetInfo()
Dim path As String = "C:\Users\XXX\Desktop\123.txt"
Dim lines As New List(Of String)
lines.AddRange(IO.File.ReadAllLines(path))
Dim tmpArray = lines(1).Split(" "c)
'******Update*******************
Dim tmplist As New List(Of String)
tmplist.Add(tmpArray(3))
tmplist.Add(tmpArray(4))
tmplist.Add(tmpArray(5))
Dim strModifiedDate As String = String.Join(" ", tmplist.ToArray) 'Get the date by joining the date, time
'************************
strModifiedDate.Text = strModifiedDate
Dim strModifiedBy As String = tmpArray(UBound(tmpArray))
strModifiedBy.Text = strModifiedBy
tmpArray = lines(2).Split(":"c)
strID.Text = tmpArray(1).Trim
Dim tmpStr As String = lines(7).Split(" "c)(0)
strOldFirstName.Text = tmpStr
tmpStr = lines(7).Substring(strOldFirstName.Text.Length).Trim
strOldLastName.Text = tmpStr
tmpStr = lines(14).Split(" "c)(0)
strNewFirstName.Text = tmpStr
tmpStr = lines(14).Substring(strNewFirstName.Text.Length).Trim
strNewLastName.Text = tmpStr
End Sub

Related

Updating values in .csv file depend to values in second .csv

I have two csv files, which contains some data. One of them looks like this:
drid;aid;1date;2date;res;
2121;12;"01.11.2019 06:49";"01.11.2019 19:05";50;
9;10;"01.11.2019 10:47";"01.11.2019 11:33";0;
72;33;"01.11.2019 09:29";"01.11.2019 14:19";0;
777;31;"03.11.2019 04:34";"03.11.2019 20:38";167,35;
Second scv looks like this
datetime;res;drid
"2019-11-01 09:02:00";14,59;2121
"2019-11-03 12:59:00";25,00;777
My target to compare day of date also "drid" and if they are the same in both files then get sum of "res" and replace values of "res" in first csv. Result have to looks like this:
2121;12;"01.11.2019 06:49";"01.11.2019 19:05";64,59;
9;10;"01.11.2019 10:47";"01.11.2019 11:33";0;
72;33;"01.11.2019 09:29";"01.11.2019 14:19";0;
777;31;"03.11.2019 04:34";"03.11.2019 20:38";192,35;
What I have to do to obtain that results in vb.net? I tried to use LINQ Query, but with no results, because I'm newbie and I didn't find way to declare variables in two files and then compare it.
Ok, with .bat I made join both csv in one big.csv and tried to obtain results from same file, but again without success. Last one code is:
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim Raplines As String() = IO.File.ReadAllLines("C:\Users\big.csv")
Dim strList As New List(Of String)
Dim readFirst As Boolean
For Each line In Raplines
If readFirst Then
Dim strValues As String() = line.Split(";")
Dim kn1 As String = strValues(0)
Dim kn2 As String = strValues(59)
Dim pvm1 As Date = strValues(2)
Dim pvm1Changed = pvm1.ToString("dd")
Dim pvm2 As Date = strValues(3)
Dim pvm2Changed = pvm2.ToString("dd")
Dim pvm3 As Date = strValues(60)
Dim pvm3Changed = pvm3.ToString("dd")
Dim Las1 As Decimal = strValues(9)
Dim Las2 As Decimal = strValues(61)
Dim sum As Decimal = Las1 - Las2
If kn1 = kn2 And pvm3Changed = pvm1Changed Or pvm3Changed = pvm2Changed Then
strValues(9) = sum
strList.Add(String.Join(";", strValues))
End If
End If
readFirst = True
Next
IO.File.WriteAllLines("C:\Users\big_new.csv", strList.ToArray())
End Sub
Instead of changing the existing file I wrote a new one. I used a StringBuilder so the runtime would not have to create and throw away so many strings. StringBuilder are mutable unlike Strings. I parsed the different formats of the dates and used .Date to disregard the Times.
Private Sub ChangeCVSFile()
Dim lines1 = File.ReadAllLines("C:\Users\someone\Desktop\CSV1.cvs")
Dim lines2 = File.ReadAllLines("C:\Users\someone\Desktop\CSV2.cvs")
Dim sb As New StringBuilder
For Each line1 In lines1
Dim Fields1 = line1.Split(";"c) 'drid;aid;1date;2date;res
For Each line2 In lines2
Dim Fields2 = line2.Split(";"c) 'datetime;res;drid
'
' Trim the exta double quotes "01.11.2019 06:49"
Dim d1 = DateTime.ParseExact(Fields1(2).Trim(Chr(34)), "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture).Date
' "2019-11-01 09:02:00"
Dim d2 = DateTime.ParseExact(Fields2(0).Trim(Chr(34)), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture).Date
If Fields1(0) = Fields2(2) AndAlso d1 = d2 Then
Dim sum = CDec(Fields1(4)) + CDec(Fields2(1))
Fields1(4) = sum.ToString
End If
Next
sb.AppendLine(String.Join(";", Fields1))
Next
File.WriteAllText("C:\Users\someone\Desktop\CSV3.cvs", sb.ToString)
End Sub

How can i find a string in a txt file and linenumber

I would like to make a "Tolerance-calculator"
The user gives an input as string. For example:"D6" now i have to search this in the .txt file and read the next line.
I read the file like this:
Dim Findstring = IO.File.ReadAllText("....\Toleranz0.txt")
How can i find the string an the next line after the string?
Maybe:
Findstring.contains("D6") 'gives a Boolean
How does i get the correct line?
Convert your string to an array using String.Split() and find the next index or 2 indexes after "D6":
Private Sub Funcy()
Dim Findstring As String = IO.File.ReadAllText("....\Toleranz0.txt")
Dim MyCollection() As String = Findstring.Split()
Dim result As String = MyCollection(Array.IndexOf(MyCollection, "D6") + 2)
MessageBox.Show(result)
End Sub
Here's an example using ReadAllLines() as suggested by Blorgbeard:
Dim lines() As String = IO.File.ReadAllLines("....\Toleranz0.txt")
Dim index As Integer = Array.IndexOf(lines, "D6")
If index <> -1 AndAlso index <= lines.Count - 2 Then
Dim targetLine As String = lines(index + 1)
' ... do something with "targetLine" ...
Else
' either the line was not found, or there was no line after the found line
End If

Read Comma Delimited String line by line for valye

I have the following code which takes a file's encrypted contents and decrypts it into a string. This is simply just a comma Delimited string like the following:
Garry, 001, 0006
Ben, 002, 00
I want to check the values in column 0 and 1 match the contents of a textbox, but It has to be on the same row hence why I need to read each row/line. I've got most of it to work, I just dont know how to read the string line by line and check it's columns, could someone help?
My commented code is just pseudo code for what I'm trying to do.
Using TextReader As New IO.StreamReader("C:\Users\Garry\Desktop\test.txt")
Dim EncryptedString As String = TextReader.ReadToEnd
Dim DecryptedString As String = AESD(EncryptedString, Password)
Dim strReader As New StringReader(DecryptedString)
Dim line As String = strReader.ReadLine
'If Line.column(0).contains(txtName.text) AND Line.column(1).contains(txtEnteredKey.text) then
'Else
'Go to next line
'End If
End Using
You can split the string by the , and then compare the columns to your desired value. For example, if I wanted to find Ben in the list, I could do this:
Dim s As String = "Garry, 001, 0006
Ben, 002, 00"
Dim strReader As New StringReader(s)
Dim line = strReader.ReadLine
While String.IsNullOrEmpty(line) = False
Dim parts = line.Split(","c)
If (parts(0).Trim() = "Ben" And parts(1).Trim() = "002") Then
Console.WriteLine("Found ben!")
Exit While
End If
line = strReader.ReadLine
End While
Console.ReadLine()
You could also do:
Dim DecryptedString As String = AESD(System.IO.File.ReadAllText("C:\Users\Garry\Desktop\test.txt"), Password)
Dim values() As String
For Each line As String In DecryptedString.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
values = line.Split(",")
If values.Length >= 2 AndAlso values(0) = txtName.Text AndAlso values(1) = txtEnteredKey.Text Then
' ... do something ...
Exit For
End If
Next

VB.net extracting values from text file

I have a text file named range.txt with the following contents:
MTN_G_ST_TT:i=67:a=89
I need to get the value 67 into a variable called gbl_min and 89 into a variable called gbl_max.
While the information in the question is woefully inadequate, here is an attempt:
Dim data As String = File.ReadAllText("range.txt") 'MTN_G_ST_TT:i=67:a=89
Dim results = Regex.Matches("[ai]=([0-9]+)(:|$)", data)
gbl_min = Integer.Parse(results.Item(0).Groups(1).Value)
gbl_max = Integer.Parse(results.Item(1).Groups(1).Value)
You read and split text:
Using sr As New IO.StreamReader("C:\\tmp\range.txt")
Dim strLineData As String = sr.ReadLine()
Dim oArr = strLineData.Split(":")
If oArr.Length = 3 Then
Dim gbl_min = oArr(1).Replace("i=", "")
Dim gbl_max = oArr(2).Replace("a=", "")
End If
End Using

Retrieve everything after a split in string VB.net

I'm needing to return the value of a string after it's been split in VB.Net.
The string will be something along the lines of:
someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5
The string can't contain more than 3 of these expressions so I need to retrieve everything after someexpression3.
After the split I would need the following "OR someexpression4 OR someexpression5", the full string will always be different lengths so I need something dynamic in order to capture the last part of the string.
Without further information on how danymic your splitting should be the following code will cover your requirement:
'Some UnitTest
Dim toSplit As String = "someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5"
Dim actual = GetLastExpressions(toSplit)
Dim expected = "OR someexpression4 OR someexpression5"
Assert.AreEqual(expected, actual)
toSplit = "requirement OR is OR weird"
actual = GetLastExpressions(toSplit)
expected = ""
Assert.AreEqual(expected, actual)
'...
Private Function GetLastExpressions(expression As String, Optional splitBy As String = "OR", Optional numberToSkip As Integer = 3)
Dim expr As String = ""
Dim lExpressions As IEnumerable(Of String) = Nothing
Dim aSplit = expression.Split({expression}, StringSplitOptions.None)
If aSplit.Length > numberToSkip Then
lExpressions = aSplit.Skip(numberToSkip)
End If
If lExpressions IsNot Nothing Then
expr = splitBy & String.Join(splitBy, lExpressions)
End If
Return expr
End Function
Spoke to a friend of mine who suggested this and it works fine;
Dim sline As String = MyString
Dim iorcount As Integer = 0
Dim ipos As Integer = 1
Do While iorcount < 17
ipos = InStr(ipos, sline, "OR")
ipos = ipos + 2
iorcount = iorcount + 1
Loop
MsgBox(Mid(sline, ipos))