Find REGEX in every file in a folder - vb.net

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

Related

Copy a File Using DragDrop VB.Net

What is wrong with my code? Getting a 'Process cannot access the file because it is being used by another process' error msg Is there a way around this. My google-fu was not giving me much luck. I was not able to Move or Copy, and I will take either.
Private Sub frmFiberTransMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub frmFiberTransMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim filePaths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
Call CopyFileDrop(filePaths)
End If
End Sub
Private Sub CopyFileDrop(filePaths As String())
For Each fileLoc As String In filePaths
Dim fileName As String = fileLoc
Dim fi As New IO.FileInfo(fileName)
File.Create(fileName)
Dim justFileName As String = fi.Name
Dim newPathName As String = gProgDir & "\" & justFileName
Directory.Move(fileLoc, newPathName)
Next fileLoc
End Sub
File.Create(fileName) returns an open handle and you're not closing it. It doesn't look like you need that line. –
#LarsTech 50 mins ago

hide folder name in tree list

how do i hide specific name folder within the treelist ? i have tree list like this
and i want to hide folder name New folder and pdf. i make this from Load Data Dir. i have tweak a bit in the code like this by putting if
Dim rootfolder As String = "C:\\FFOutput"
Private Sub TreeList1_VirtualTreeGetCellValue(ByVal sender As Object, ByVal e As DevExpress.XtraTreeList.VirtualTreeGetCellValueInfo) Handles TreeList1.VirtualTreeGetCellValue
Dim di As New DirectoryInfo(CStr(e.Node))
If di.Name <> "New folder" Then
If e.Column Is TreeListColumn1 Then
e.CellData = di.Name
End If
If e.Column Is TreeListColumn2 Then
e.CellData = e.Node.ToString
End If
If e.Column Is TreeListColumn3 Then
If IsFile(di) Then
e.CellData = New FileInfo(CStr(e.Node)).Extension
Else
e.CellData = Nothing
End If
End If
End If
End Sub
Private Sub TreeList1_VirtualTreeGetChildNodes(ByVal sender As Object,
ByVal e As DevExpress.XtraTreeList.VirtualTreeGetChildNodesInfo) _
Handles TreeList1.VirtualTreeGetChildNodes
If loadDrives = False Then
Dim root As String() = Directory.GetDirectories(rootfolder)
e.Children = root
loadDrives = True
Else
Try
Dim di As New DirectoryInfo(CStr(e.Node))
If di.Name <> "New folder" Then
Dim path As String = CStr(e.Node)
If Directory.Exists(path) Then
Dim dirs As String() = Directory.GetDirectories(path)
Dim files As String() = Directory.GetFiles(path)
Dim arr(dirs.Length + files.Length) As String
dirs.CopyTo(arr, 0)
files.CopyTo(arr, dirs.Length)
e.Children = arr
Else
e.Children = New Object() {}
End If
End If
Catch
End Try
End If
End Sub
and it become like this

how to prefix filenames recursively and output to a folder

right this one is driving me mental. I'm sure I'm doing something unbelievably stupid but I can't work it out. I'm trying to copy every file within a directory structure and rename it with it's source directory, output into a single folder. my code seems to do nothing. Help!!!
Imports System.IO
Public Class Form1
Dim projDirectory As String = "C:\Users\phil\Desktop\satdoc software trial folders\test project folder"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ProjArray = IO.Directory.GetDirectories(projDirectory)
ComboBox1.MaxDropDownItems = ProjArray.Length
For Each proj As String In ProjArray
proj = proj.Substring(proj.LastIndexOf("\") + 1)
ComboBox1.Items.Add(proj) 'populate combobox with list of projects in folder
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim projfolder As New DirectoryInfo(projDirectory & "\" & ComboBox1.SelectedItem)
finalise(projfolder)
End Sub
Private Sub finalise(ByVal folder As DirectoryInfo)
Try
Dim files = folder.GetFiles
For Each file In files
Dim pos1 = InStr(file.Name, ComboBox1.SelectedItem) - 1 'position in string marks beginning of project name
Dim pos2 = file.Name.LastIndexOf("\") ' position in string marks last subfolder
Dim NoofChars As Integer = pos2 - pos1 'number of chars to use from full string
Dim filenameappend = file.Name.Substring(pos1, NoofChars) 'select the appropriate chars
Dim append As String = filenameappend.Replace("\", " ") 'replace all teh \ with spaces
file.CopyTo(projDirectory & "\output\" & append & file.Name) 'copy to another folder and prefix the filename with the filestructure of its parent project
Label1.Text = append
Next
For Each subfolder In folder.GetDirectories
finalise(subfolder) 'recursive through all folders
Next
Catch e As Exception
End Try
End Sub
End Class

How to get line number from a text file in 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

Print Preview not displaying file

I am working on a menu strip Print Preview event. i worked out the following procedure to view a pdf file located in the same path as my workbook.
Private WithEvents docPrint As New PrintDocument()
' Declare a string to hold the entire document contents.
Private documentContents As String
' Declare a variable to hold the portion of the document that
' is not printed.
Private stringToPrint As String
Private Sub ReadDocument()
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
Dim stream As New FileStream(docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
documentContents = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
stringToPrint = documentContents
End Sub
Private Sub prnPrvStripCustomRange_Click(sender As Object, e As EventArgs) Handles prnPrvStripCustomRanges.Click
ReadDocument()
prnPrvCustomRanges.Document = docPrint
prnPrvCustomRanges.ShowDialog()
End Sub
The dialog pops up on click, but my document page is blank. I have another event for printing and that one prints the same document. So I don't understand what I am doing wrong on my preview.
Here is my print procedure:
Private Sub prnCustonPages_Click(sender As Object, e As EventArgs) Handles prnCustonPages.Click
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
prnPrtCustomRanges.Document = docPrint
prnPrtCustomRanges.PrinterSettings = docPrint.PrinterSettings
prnPrtCustomRanges.AllowSomePages = True
If prnPrtCustomRanges.ShowDialog = DialogResult.OK Then
docPrint.PrinterSettings = prnPrtCustomRanges.PrinterSettings
docPrint.Print()
End If
End Sub