VB.net program to grab lines from files that contain a certain text pattern
I have the following code that iterates thru files ending in .dat within a folder. Now what I want to do is go into each file and grab one line at a time, and if that line contains "PO-", then I want to put it into an array. I'm thinking I need another loop (maybe another Next loop?). Can someone help me to grab lines containing "PO-" within these files and put them into an array? Thanks!
Private Sub btnSaveReport_Click(sender As Object, e As EventArgs) Handles btnSaveReport.Click Try Dim arrayPOentries() As String Dim strSourceFileLocation As String = AppDomain.CurrentDomain.BaseDirectory + "_data/" Dim strDetinationFileLocation As String = tbSaveFileLocation.Text Dim Paths() As String = IO.Directory.GetFiles(strSourceFileLocation, "*.dat") For Each Path As String In Paths 'another loop here? Next Catch ex As Exception MessageBox.Show(ex.Message) End Try Me.Close() End Sub
Oh thank you so much, this is awesome! I was trying this Do loop and getting an "object reference not set to an instance of an object" error. Your code is much cleaner.
Private Sub btnSaveReport_Click(sender As Object, e As EventArgs) Handles btnSaveReport.Click Try Dim strSourceFileLocation As String = AppDomain.CurrentDomain.BaseDirectory + "_data/" Dim strDetinationFileLocation As String = tbSaveFileLocation.Text Dim Paths() As String = IO.Directory.GetFiles(strSourceFileLocation, "*.dat") For Each Path As String In Paths Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(Path) Dim strLine As String Do strLine = reader.ReadLine If strLine.Contains("PO-") Then MsgBox(strLine) End If Loop Until strLine Is Nothing reader.Close() Next Catch ex As Exception MessageBox.Show(ex.Message) End Try Me.Close() End Sub
Open in new window