How can i find a string in a txt file and linenumber - vb.net

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

Related

get full string before first second third etc. split

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

vb.net how to find a range of digits in string

I would like to split a String by a range of digits (0 to 20) and the letters should be .toLower
How can I define the range in my code?
I have tried to do it like this:("0","1","2","3")
Dim Tolerancevalueofext As String = "JS12"
Dim removenumber As String = Tolerancevalueofext.Substring(0, Tolerancevalueofext.IndexOf("0","1","2","3")).ToLower
But that is definitely wrong.
your request i quite unclear but here is a way to:
1. extract only numbers from string (using Regex).
2. extracting only letters from string that contains digits and converting them to small letters.
Private Sub Example()
Dim Tolerancevalueofext As String = "JS12"
' only numbers, output: "12"
Dim onlynumbers As String = extractNumberFromString(Tolerancevalueofext).ToString()
' only characters, output: "js"
Dim onlycharacters As String = String.Empty
For Each line As String In Tolerancevalueofext
If Not (IsNumeric(line)) Then
onlycharacters += line.ToLower()
End If
Next
End Sub
Public Shared Function extractNumberFromString(ByVal value As String) As Integer
Dim returnVal As String = String.Empty
Dim collection As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(value, "\d+")
For Each m As System.Text.RegularExpressions.Match In collection
returnVal += m.ToString()
Next
Return Convert.ToInt32(returnVal)
End Function
Output: onlynumbers = "12" onlycharacters = "js"

Getting the character that inside the brackets

This is my string:
Dim value as string = "IR_10748(1).jpg"
How can I get this number 1 into another variable? I am thinking to use split.
How I can use to get this value in vb.net?
See String.Substring(Integer, Integer) and String.IndexOf(String).
Dim value As String = "IR_10748(1).jpg"
Dim startIndex As Integer = value.IndexOf("(") + 1
Dim length As Integer = value.IndexOf(")") - startIndex
Dim content As String = value.Substring(startIndex, length)
Regular expressions might be cleaner. This should work:
dim Result as string = Regex.Match(value, "(?<=\().*(?=\))").Value
It'll extract one or more characters contained between the parentheses.
Try this:
Dim value as String = "IR_10748(1).jpg"
Dim splitStrings() as String
'Split on either opening or closing parenthesis -
'This will give 3 strings - "IR_10748","1",".jpg"
splitStrings = value.Split(New String() {"(",")"}, StringSplitOptions.None)
'Parse as integer if required
Dim i as Integer
i = Integer.Parse(splitStrings(1))
Demo
It's not the prettiest, but this gets "1" using Remove and Split :
Dim value as String = "IR_10748(1).jpg"
Dim num As String = value.Remove(0, value.IndexOf("(") + 1).Split(")")(0)
That gives num = "1"
You can get the number more reliably than using String.Split. You'll want to use LastIndexOf to get the final opening parenthesis just in case you have a filename like "a(whatever)(1).ext", and you should inspect the filename without its extension, in case you have a filename like "a(1).(9)":
Dim value As String = "IR_10748(1).jpg"
Dim fn = Path.GetFileNameWithoutExtension(value)
Dim lastOpen = fn.LastIndexOf("(")
If lastOpen >= 0 Then
Dim length = fn.IndexOf(")", lastOpen + 1) - lastOpen - 1
If length >= 1 Then
Dim numAsString = fn.Substring(lastOpen + 1, length)
Console.WriteLine(numAsString)
ElseIf length = 0 Then
' do something if required
Console.WriteLine("No number in the parentheses.")
Else
' do something if required
Console.WriteLine("No closing parenthesis.")
End If
Else
' do something if required
Console.WriteLine("No opening parenthesis.")
End If

Copying data from text file to array

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()

vb.net searching for a search within a string

lot_no = "lot123"
s.indexof("lot123") does not return zero
whereas
s.indexof(lot_no) returns zero
has anyone seen a problem like this?
what does s contain?
For Each s As String In split1
K, looked add the code in your other thread.
When I execute the following code I get a result, what am I doing wrong?
Public lot__no As String = "<Lot no>928374</Lot no>"
Sub DoSomething()
Dim temp_string As String = "<beginning of record>ETCETCETC"
Dim myDelims As String() = New String() {"<beginning of record>"}
Dim Split() As String = temp_string.Split(myDelims, StringSplitOptions.None)
For Each s As String In Split
If InStr(s, lot__no) <> 0 Then
Debug.WriteLine("found" + s)
End If
Next
End Sub
Not sure what you're asking but this code returns -1 / -1
Dim lotnr As String = "lot123"
For Each s As String In "123asd"
Debug.WriteLine(s.IndexOf("lot123"))
Debug.WriteLine(s.IndexOf(lotnr))
Next
Use IndexOf this way:
Dim lotnr As String = "lot123"
For Each s As String In "123asd"
Debug.WriteLine("lot123".IndexOf(s))
Debug.WriteLine(lotnr.IndexOf(s))
Next
This results in:
3
3
4
4
5
5
-1
-1
-1
-1
-1
-1