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
Related
I am a beginner in VB.NET and i am trying to extract data from an API and add it to a listview column but i don't know how to extract the data.
[This is the API][1]
[1]: https://tmnf.exchange/api/tracks?author=lolsport&count=40&fields=TrackId%2CTrackName
It is a API for downloading race tracks for Trackmania.
The data is shown as follows {"TrackId":9707620,"TrackName":"lolsport R444"},
Now what i need is the TrackIDs and TrackNames.
i have two columns in my program where i want to sort them into like so.
**TrackID** **TrackName**
9707620 lolsport R444
How can i do this? i googled a lot about regular expressions but i cant seem to find anything that works.
Dim Data As String = "{""TrackId"":9707620,""TrackName"":""lolsport R444""}"
Dim dataaray() As String = Data.Split(",")
Dim dataval() As String
Dim fileloc As String = Environment.CurrentDirectory & "\Test.txt"
If Not File.Exists(fileloc) Then
File.Create(fileloc).Dispose()
Else
File.Delete(fileloc)
File.Create(fileloc).Dispose()
End If
Dim objwriter As New StreamWriter(fileloc, True)
Dim i As Int32 = 0
Dim val As String
objwriter.WriteLine("**TrackID** **TrackName**")
For Each rw As String In dataaray
dataval = rw.Split(":")
val += dataval(1).Replace("""", "").Replace("}", "") & vbTab
If i = 1 Then
objwriter.WriteLine(val.TrimEnd())
val = String.Empty
i = 0
End If
i += 1
Next
objwriter.Close()
objwriter.Dispose()
I have a file location and I need to check if it exists.
The way I wan't to do it is like this:
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
For count2 As Integer = 0 To counting - 1
Dim firstbackslash As Integer = route.IndexOf("\")
Dim backslash As Integer = route.IndexOf("\", firstbackslash + 1)
Dim firstPart As String = route.Substring(0, backslash)
MsgBox(firstPart)
Next
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
But I cant find something like this on the internet nor with some messing around...
Here is an algorithm that that will give you all the paths starting from the root and building up to the final path including the filename. You can use this to check for each folder and create them as you go if they don't exist:
Sub Main()
Dim route As String = ("C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt")
Dim fi As New System.IO.FileInfo(route)
If Not fi.Exists Then
Dim fileName As String = Path.GetFileName(route)
Dim di As DirectoryInfo = fi.Directory
Dim pathStack As New Stack(Of String)()
pathStack.Push(di.Name)
While Not IsNothing(di.Parent)
di = di.Parent
pathStack.Push(di.Name)
End While
Dim curPath As String = ""
While pathStack.Count > 0
curPath = Path.Combine(curPath, pathStack.Pop)
' ... do something with "curPath" in here ...
' ... like check for existence and create it ...
Console.WriteLine(curPath)
End While
curPath = Path.Combine(curPath, fileName)
' ... do something with "curPath" in here ...
' ... this is the full path including the file on the end ...
Console.WriteLine(curPath)
End If
Console.Write("Press Enter to quit...")
Console.ReadLine()
End Sub
Output:
C:\
C:\testing1
C:\testing1\testing2
C:\testing1\testing2\testing3
C:\testing1\testing2\testing3\testing4
C:\testing1\testing2\testing3\testing4\testing5
C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt
Press Enter to quit...
Don't use string mnaipulation to work with file or folder paths. use the Path class.
One option:
Private Function GetExistingSubPath(fullPath As String) As String
If Directory.Exists(fullPath) OrElse File.Exists(fullPath) Then
Return fullPath
End If
Dim subPath = Path.GetDirectoryName(fullPath)
If subPath Is Nothing Then
Return Nothing
End If
Return GetExistingSubPath(subPath)
End Function
Sample usage:
Dim fullPath = "C:\testing1\testing2\testing3\testing4\testing5\TEXTBESTAND.txt"
Dim existingSubPath = GetExistingSubPath(fullPath)
Console.WriteLine(existingSubPath)
What I try to accomplisch is that I fist check if folder "C:" exists then "C:\testing1" then "C:\testing1\testing2" etc.
Noooooooooooo!
That's not how to do it at all! The file system is volatile: things can change between each of those checks. Moreover, file existence is only one of many things that can stop file access.
It's much better practice to try to access the file in question, and then handle the exception if it fails. Remember, because of the prior paragraph you have to be able to handle exceptions here anyway. .Exists() doesn't save you from writing that code. And each check is another round of disk access, which is about the slowest thing it's possible to do in a computer... even slower than unrolling the stack for an exception, which is the usual objection to this idea.
I fixed it, know I can check if multiple text files are at the locations I need, if there not I place the Textfiles at the location I need them. Then I can add something in it. (I need to put a Location of something else in it.)
Dim een As String = "C:\testing1\testing2\testing7\testing1\testing1\text.txt"
Dim twee As String = "C:\testing1\testing2\testing7\testing2\testing1\text.txt"
Dim drie As String = "C:\testing1\testing2\testing7\testing3\testing1\text.txt"
Dim vier As String = "C:\testing1\testing2\testing7\testing4\testing1\text.txt"
Dim Files As String() = {een, twee, drie, vier}
For Each route As String In Files
If System.IO.File.Exists(route) Then
MsgBox("BESTAAT HET WERKT!")
Else
Dim subroute() As String = route.Split("\"c)
Dim counting As Integer = route.Split("\"c).Length - 1
Dim tel As Integer = route.Substring(route.LastIndexOf("\") + 1).Count
Dim bestandnaam As String = route.Substring(route.LastIndexOf("\") + 1)
For count2 As Integer = 0 To route.Length - tel - 1
Dim firstbackslash As Integer = route.IndexOf("\", count2)
Dim backslash As Integer = route.IndexOf("\", count2)
Dim Mapnaam As String = route.Substring(0, backslash)
count2 = firstbackslash
If System.IO.Directory.Exists(Mapnaam) Then
Else
System.IO.Directory.CreateDirectory(Mapnaam)
End If
Next
If System.IO.File.Exists(route) Then
Else
Dim objStreamWriter As System.IO.StreamWriter
objStreamWriter = New System.IO.StreamWriter(route)
Dim label As String
Select Case route
Case een
label = "een"
Case twee
label = "twee"
Case drie
label = "drie"
Case vier
label = "vier"
End Select
Dim value As String = InputBox("Route invullen naar " & label)
'Dim objStreamWriter As New System.IO.StreamWriter(route)
objStreamWriter.Write(value)
objStreamWriter.Close()
'Using sw As System.IO.StreamWriter = System.IO.File.AppendText(route)
' sw.WriteLine(value)
'End Using
End If
End If
Next route
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
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
I'm trying to copy data from text file to array, I got error Index was outside the bounds of the array.
Dim vstring(-1) As String
Dim vid(-1) As String
Dim index As Integer
Dim vText As String = ""
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
Dim vAvgValue As Integer
Dim vErrorMsg As String = ""
If (Txt_IdNumber.Text).Length = 5 Then
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
vstring = vText.Split(",")
vid(index) = vstring(0)'error
index = index + 1
Loop
Dim vstring() as String
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
If Txt_IdNumber.Text.Length = 5 Then
Using rvSR As New IO.StreamReader(vFileName)
vstring = rvSR.ReadLines().Select(Function(s) s.Split(","c)(0)).ToArray()
End Using
End If
First, you should probably declare vstring as an unsized array. Like this:
Dim vString() as string
Second, Since you don't know how many lines you need, declare vid as list. Like this:
Dim vid as List(of string)
Then, before you split the string, you should make sure it actually contains a comma. Like this:
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
If vText.Contains(",") Then
vstring = vText.Split(",")
vid.add(vstring(0))
End If
Loop
'at the end, you can convert vid from a list to an array, if you want
Dim arr() as string = vid.ToArray()