How to get line number from a text file in vb.net - vb.net

I am making a program where i have 2 text files and i want 2 get one line from each text file like this
Dim pathlocal as string= Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Test\"
Dim reader As New System.IO.StreamReader(pathlocal & "to.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
For Each file In allLines
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(file).Name) Then
'Get line number of from.txt where you found file.name
End If
End If
Next
I appreciate the help(and pls try 2 make it simple sorry but i am not that good THANX)

This might help you:
Imports System.IO
Imports System
Imports System.Collections.Generic
Public Class Form1
Dim path As String = "Your Path"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim indxto As Integer = 0
Dim indxfrom As Integer = 0
Dim allLinesto As List(Of String) = File.ReadAllLines(path & "\" & "to.txt").ToList
Dim allLinesfrom As List(Of String) = File.ReadAllLines(path & "\" & "from.txt").ToList
For Each line As String In allLinesto
indxto = allLinesto.IndexOf(line)
'Debug.Print(line & " " & indxto.ToString)
For Each item As String In allLinesfrom
indxfrom = allLinesto.IndexOf(item)
If line = item Then
Debug.Print(item & " " & indxfrom.ToString)
End If
Next
Next
End Sub
End Class

You can instantiate a couple of Integer typed variables to help with this. One stores the line number as you iterate through the list and the other stores the line number you are seeking. Plus, by changing your For Each approach to a Do Until or Do While approach you could potentially speed things up if the target is found prior to the last line of the file.
Dim intLineNumber As Integer = -1
Dim intLineCursor As Integer
Do Until (intLineCursor = allLines.Count OrElse intLineNumber <> -1)
If pathlocal & "from.txt".Contains(My.Computer.FileSystem.GetFileInfo(allLines(intLineCursor)).Name) Then
intLineNumber = intLineCursor '+ 1 if you are displaying to a user since the lower bound is 0 based.
End If
'Increment the cursor variable.
intLineCursor += 1
Loop

Related

Find REGEX in every file in a folder

I need to evaluate each file in a folder for the ICN string. Then add each ICN to an output file. I found the code below and have made changes to it to meet my needs but it only adds one found file in the ICN.log instead of looping through all files.
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Dim Regex = New Regex("[<][!]ENTITY (ICN.*?)[.]\w+")
Dim output = New List(Of String)
Dim tLoc = txtFolderPath.Text
Dim txtFiles = Directory.EnumerateFiles(tLoc, "*.xml", SearchOption.AllDirectories)
For Each tFile In txtFiles
Dim input = File.ReadAllText(tFile)
If Regex.IsMatch(input) Then
Console.Write("REGEX found in " + tFile)
output.Add(tFile)
Exit For
End If
Next
File.WriteAllLines(tLoc.TrimEnd("\"c) & "\ICN.log", output)
End Sub
After I removed the for exit for the code works.
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Dim Regex = New Regex("[<][!]ENTITY (ICN.*?)[.]\w+")
Dim output = New List(Of String)
Dim tLoc = txtFolderPath.Text
Dim txtFiles = Directory.EnumerateFiles(tLoc, "*.xml", SearchOption.AllDirectories)
For Each tFile In txtFiles
'MsgBox(tFile)
Dim input = File.ReadAllText(tFile)
If Regex.IsMatch(input) Then
Console.Write("REGEX found in " + tFile)
output.Add(tFile)
'Exit For
End If
Next
File.WriteAllLines(tLoc.TrimEnd("\"c) & "\ICN.log", output)
MsgBox("Function Complete")
End Sub

How to create a progress bar that updates simultaneously with a file transfer

As the title implies, I am trying to create a progress bar that updates with a file transfer. I am currently using Visual Studio 2019. I have been through dozens of articles and videos all claiming to do just this. After many days of testing, I have gotten close, but the progress bar will still only update after the file transfer is complete. I am using multi threading techniques to accomplish just this much. I would very much appreciate if someone could just lay it down for me on how to do this. Here is my code so far. It doesn't really help for making it but you can at least see what I am trying to achieve. I also left out some large chunks of commented out test script.
Summary of what I need to is: Create a script that will copy the specified directory and all sub directories. While doing this I would like the progress bar to move with the file transfer.
Imports System.ComponentModel
Imports System.Threading
Imports System
Imports System.IO
Public Class Form1
Private Sub BtnStartTransfer_Click(sender As Object, e As EventArgs) Handles btnStartTransfer.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Delegate Sub DelegateProgressBarMax(ByVal check As Integer)
Private Sub ProgressBarUpdate(ByVal check As Integer)
If pBar1.InvokeRequired = True Then
Invoke(Sub() pBar1.Value = check)
Else
pBar1.Value = check
End If
End Sub
Private Delegate Sub DelegateUpdateOutput(ByVal check2 As String)
Private Sub OutputUpdate(ByVal check2 As String)
If txtOutput.InvokeRequired = True Then
Invoke(Sub() txtOutput.Text = txtOutput.Text & check2 & Environment.NewLine)
Else
txtOutput.Text = txtOutput.Text & check2
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim getCopyFrom As String = txtCopyFrom.Text
Dim getCopyTo As String = txtCopyTo.Text
Dim splitUser() As String = getCopyFrom.Split("\")
Dim finalValue As String = splitUser.Length - 1
Dim stringValue As String = CStr(splitUser(finalValue))
Dim getUser As String
'If MsgBox("Is this the correct user?: " & stringValue, vbYesNo + vbQuestion) = vbYes Then
' getUser = stringValue
'Else
' getUser = InputBox("Enter in the correct Username")
'End If
Dim checkCopyFrom As New IO.DirectoryInfo(getCopyFrom)
Dim checkCopyTo As New IO.DirectoryInfo(getCopyTo)
If checkCopyFrom.Exists Then
Else
MsgBox("The location you are trying to copy from does not exist.")
Exit Sub
End If
If checkCopyTo.Exists Then
Else
MsgBox("The location you are trying to copy to does not exist.")
Exit Sub
End If
'Copying the Desktop folder
Dim dirDesktop = getCopyFrom & "\Desktop"
Dim getDir = IO.Directory.GetFiles(dirDesktop, "*", IO.SearchOption.AllDirectories)
Dim fileTotal As Integer = getDir.Length
Dim filesTransferred As Integer = 0
Dim di As New DirectoryInfo(dirDesktop)
Dim fiArr As FileInfo() = di.GetFiles("*", SearchOption.AllDirectories)
Dim diArr As DirectoryInfo() = di.GetDirectories("*", IO.SearchOption.AllDirectories)
Dim fri As FileInfo
Dim fol As DirectoryInfo
For Each fri In fiArr
filesTransferred += 1
BackgroundWorker1.ReportProgress(CInt(filesTransferred * 100 \ fiArr.Length), True)
OutputUpdate(fri.Name)
'File.Copy(dirDesktop & "\" & fri.Name, getCopyTo & "\" & fri.Name, True)
'My.Computer.FileSystem.CopyDirectory(getCopyFrom & "\Desktop", getCopyTo & "\Users\" & getUser & "\Desktop", False)
Next fri
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
pBar1.Value = e.ProgressPercentage
End Sub

Type expected error VB.Net

Error ImagePlease assist, I get a "Type expected" error on my code for a windows based application. I get the error on this line "Dim objSW As New StreamWriter(objFS)"
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Dim objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim objSW As New StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
objSW.Close()
End Sub
End Class
The problem is that you have named your project "StreamWriter", which causes "StreamWriter" to refer to the namespace of the project. Maybe you should use more a bit more descriptive project names in the future just for clarity?
You can fix this by referring to the real StreamWriter with namespace:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Using objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Using objSW As New System.IO.StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
End Using
End Using
End Sub
End Class
Ps. Added the using-statements that should always be used with iDisposable-objects. Removed the unnecessary close-call also.

Text file manipulation using visual basic

Hi I am looking for a way to take a text file that has 1 set of numbers per line and make a new text file that has taken the set of numbers and put them into 2 spaced out columns per line. Using Visual Basic 2010 Ex:
My First text file will look similar to this: test1.txt
12345
23456
34567
45678
56789
67890
But I would like to convert it to look like this and save it as a new file: text2.txt
12345 23456
34567 45678
56789 67890
With more spacing in between the set of numbers. I have been struggling with this for about a week now and I have put myself back at square one with it. Thank you all for your time and hope you all have a good day. Joe.
Here is my current code. I am embarrassed to say the least. I am taking an exsisting file and formatting it to have a space between each line of numbers and then reading it into a richtextbox to convert it to a barcode font then saving it. At that point I have no idea how to make the format the way I need it to be putting 2 sets of numbers on one line.
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnLoad.Click
ListBox1.Items.AddRange(IO.File.ReadAllLines("C:\test\serintest.txt"))
End Sub
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnConvert.Click
Dim FILE_NAME As String = "C:\test\serscantemp.rtf"
Dim i As Integer
Dim t As Integer
TextBox1.Text = ListBox1.Items.Count.ToString(t)
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
For i = 0 To TextBox1.Text - 1
'objWriter.WriteLine(aryText(i))
objWriter.WriteLine(ListBox1.Items(i))
objWriter.WriteLine("")
Next
objWriter.Close()
Me.RichTextBox.LoadFile("C:\test\serscantemp.rtf", _
RichTextBoxStreamType.PlainText)
RichTextBox.SaveFile("c:\test\barcodetext.rtf", _
RichTextBoxStreamType.RichText)
End Sub
Joe,
Try this.
I am concatenating the numbers into a string variable and keeping a counter. If the counter = 2 then i write out the concatenated string to RichTextBox and clear counter and string variable
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
Dim FILE_NAME As String = "C:\temp\serscantemp.rtf"
Dim i As Integer
Dim t As Integer
Dim s As String
Dim c As Integer
TextBox1.Text = ListBox1.Items.Count.ToString(t)
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
c = 0
s = ""
For i = 0 To TextBox1.Text - 1
c = c + 1
If s > "" Then
s = s & " "
End If
s = s & ListBox1.Items(i)
If c = 2 Then
objWriter.WriteLine(s)
objWriter.WriteLine("")
s = ""
c = 0
End If
'objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
RichTextBox1.LoadFile("C:\temp\serscantemp.rtf", _
RichTextBoxStreamType.PlainText)
RichTextBox1.SaveFile("c:\temp\barcodetext.rtf", _
RichTextBoxStreamType.RichText)
End Sub
I hope this is what you are looking for.
Here's another way to do it that you might also want to try though almost the same as Ed's answer. Just call the routine from btnConvert click event. Also make sure to include Import System.IO
Private Sub Reformat(sourceFile As String, destFile As String)
Dim arr As String() = File.ReadAllLines(sourceFile)
Dim s As String = String.Empty
Dim lst As New List(Of String)()
Dim iCtr As Integer = 0
For i As Integer = 0 To arr.Length - 1
If Not String.IsNullOrWhiteSpace(arr(i)) Then
s += arr(i) & " "
iCtr += 1
If iCtr = 2 Then
lst.Add(s.Trim())
iCtr = 0
s = String.Empty
End If
End If
Next
If Not String.IsNullOrWhiteSpace(s.Trim()) Then
lst.Add(s)
End If
File.WriteAllLines(destFile, lst.ToArray())
End Sub
By the way, this is my first post in SO. Just saying.

VB.net multithreading for loop, parallel threads

I have a simple form with 2 RichTextBoxes and 1 button, the code grabs the url address from RichTextBox1 and phrases the page for the title field using regex and appends it to RichTextBox2. I want to multithread everything in such way that none of the url's are skipped and the thread numbers can be set ( according to the system free resources ) For example, let's say 10 threads to run in parallel. I searched everything and the best that I managed to do is run everything in a background worker and keep the GUI from freezing while working. A short code sample will be of much help, I am a beginner in VB.net.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 0 To RichTextBox1.Lines.Length - 1
If RichTextBox1.Lines(i).Contains("http://") Then
Dim html As String = New System.Net.WebClient() _
.DownloadString(RichTextBox1.Lines(i))
Dim pattern As String = "(?<=\<title\>)([^<]+?)(?=\</title\>)"
Dim match As System.Text.RegularExpressions.Match = _
System.Text.RegularExpressions.Regex.Match(html, pattern)
Dim title As String = match.Value
RichTextBox2.AppendText(title & vbCrLf)
End If
Next
End Sub
End Class
Updated code ( throwing "Index was outside the bounds of the array." errors. )
Imports System
Imports System.Threading
Public Class Form1
Public Sub test(ByVal val1 As String, ByVal val2 As String)
Dim zrow As String
zrow = RichTextBox1.Lines(val1)
If zrow.Contains("http://") Then
Dim html As String = New System.Net.WebClient().DownloadString(zrow)
Dim pattern As String = "(?<=\<title\>)([^<]+?)(?=\</title\>)"
Dim match As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(html, pattern)
Dim title As String = match.Value
RichTextBox2.AppendText(val2 & title & vbCrLf)
End If
End Sub
Public Sub lastfor(ByVal number)
Dim start As Integer = number - 100
For x = start To number - 1
Try
test(x, x)
RichTextBox2.AppendText(x & RichTextBox1.Lines(x).Trim & vbCrLf)
Catch ex As Exception
'MsgBox(ex.Message)
RichTextBox3.AppendText(ex.Message & vbCrLf & vbCrLf)
End Try
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim TotalLines As String = RichTextBox1.Lines.Length - 1
Dim TotalThreads As Integer = 10
Dim LinesPerThread As Integer = TotalLines / TotalThreads
Dim increment As String = LinesPerThread
Dim zdata(TotalThreads) As String
For i = 0 To TotalThreads - 1
zdata(i) = increment
increment = increment + LinesPerThread
Next
Dim lst As New List(Of Threading.Thread)
For Each bump As String In zdata
Dim t As New Threading.Thread(Function(l As String)
'Do something with l
'Update GUI like this:
If bump = String.Empty Or bump Is Nothing Then
Else
lastfor(l)
'MsgBox(l)
End If
End Function)
lst.Add(t)
t.Start(bump)
Next
'test(1)
End Sub
End Class
There are two ways two achieve this:
First, if you are using .NET 4.0, you could use a Parallel.ForEach loop:
Parallel.ForEach(RichTextBox1.Lines, Function(line As String)
' Do something here
' To update the GUI use:
Me.Invoke(Sub()
' Update GUI like this...
End Sub)
Return Nothing
End Function)
The other way is to do this manually (and you will have slightly more control):
Dim lst As New List(Of Threading.Thread)
For Each line In RichTextBox1.Lines
Dim t As New Threading.Thread(Function(l As String)
'Do something with l
'Update GUI like this:
Me.Invoke(Sub()
'Update Gui...
End Sub)
End Function)
lst.Add(t)
t.Start(line)
Next
Both of these are very crude, but will get the job done.
EDIT:
Here is a sample code that will control the number of threads:
Dim lst As New List(Of Threading.Thread)
Dim n As Integer = 1 ' Number of threads.
Dim npl As Integer = RichTextBox1.Lines / n
Dim seg As New List(Of String)
For Each line In RichTextBox1.Lines
For i = npl - n To npl
seg.Add(RichTextBox1.Lines.Item(i))
Next
Dim t As New Threading.Thread(Function(l As String())
For Each lin In l
' TO-DO...
Next
'Do something with l
'Update GUI like this:
Me.Invoke(Sub()
'Update Gui...
End Sub)
End Function)
lst.Add(t)
t.Start(seg.ToArray())
Next
*The above code might have bugs.