|
-
Dec 13th, 2023, 10:05 AM
#1
Thread Starter
Addicted Member
VB.NET Search Multiple Files for String, Count Duplicates, Return Filename & Qty
Hi All.. I am using some old VBA code that I am trying to convert over to .NET but having a hard time doing what I need. In this case, I am searching a single folder with hundreds of files for a string. I need to find how many times that string is found in the file, return the filename with the quantity found. Here is what I have started with, but this fails after returning the first filename and entering it to the listbox. I have not gotten as far yet as getting the total counts and filename returned. Any guidance on this would be greatly appreciated.
Code:
Dim fpath = Directory.GetCurrentDirectory
Dim filesPath = fpath & "\prg"
Private Sub btnSearchFiles_Click(sender As Object, e As EventArgs) Handles btnSearchFiles.Click
Dim thePart = $" {TextBox1.Text} " 'match whole word
Dim di As New DirectoryInfo(filesPath)
For Each fi As FileInfo In di.GetFiles()
If File.ReadAllText(fi.FullName).Contains(thePart) Then
ListBox1.Items.Add(fi.Name)
MsgBox(fi.Name)
Dim lines As New HashSet(Of String)()
Using sr As StreamReader = New StreamReader(fi.Name)
Do While sr.Peek() >= 0
lines.Add(sr.ReadLine())
ListBox1.Items.Add(lines)
Loop
End Using
End If
Next
End Sub
Trying more things today with no luck... Going crazy here. I hope someone can help me with this.
Code:
Dim fpath = Directory.GetCurrentDirectory
Dim filesPath = fpath
Private Sub btnSearchFiles_Click(sender As Object, e As EventArgs) Handles btnSearchFiles.Click
Dim thePart = $" {TextBox1.Text} " 'match whole word
Dim di As New DirectoryInfo(filesPath)
Dim strText As String = SearchFile(di.FullName, thePart)
If strText <> String.Empty Then
ListBox2.Items.Add(strText)
End If
End Sub
Public Shared Function SearchFile(ByVal filesPath As String, ByVal thePart As String) As String
Dim sr As StreamReader = New StreamReader(filesPath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(thePart) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
Last edited by mikeg71; Dec 14th, 2023 at 10:23 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|