How to search for a string within a specific range of characters within a file name by DirectoryInfo class?
I only need to select files that have "inscriz" in the character range 22 to 29
This is my code:
Public Sub SpostaFile(sourceDirectory As String, ByVal destDirectory As String)
Try
Dim from_date As DateTime = DateTime.Now.AddHours(-24)
Dim to_date As DateTime = DateTime.Now.AddHours(+24)
Try
Dim folder As New DirectoryInfo(sourceDirectory)
Dim pdfList = folder.EnumerateFiles("*.PDF").Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date)
Dim xlsList = folder.EnumerateFiles("*.XLS").Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date)
Dim xlsxList = folder.EnumerateFiles("*.XLSX").Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date)
Dim csvList = folder.EnumerateFiles("*.csv").Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date)
' Copy pdf files.
For Each file In pdfList
file.CopyTo(Path.Combine(destDirectory, file.Name))
Next
' Copy XLS files.
For Each file In xlsList
file.CopyTo(Path.Combine(destDirectory, file.Name))
Next
' Copy XLSX files.
For Each file In xlsxList
file.CopyTo(Path.Combine(destDirectory, file.Name))
Next
' Copy CSV files.
For Each file In csvList
file.CopyTo(Path.Combine(destDirectory, file.Name))
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Convert this:
Dim pdfList = folder.EnumerateFiles("*.PDF").Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date)
to this:
Dim pdfList = folder.EnumerateFiles("*.PDF").
Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date AndAlso
fi.Name.Length >= 29 AndAlso fi.Name.Substring(22,7) = "inscriz" )
and do the same for the other file types.
I'll add a note that the question text says to search in the range between character 22 and 29, which is a 7 characters long, for set of text that is also seven characters. In that case, we can do a simple equality comparison. If the range were longer, we would use .Contains()
instead.
I might also be tempted to do this, to avoid repetition, but there's a good argument to be made this is overkill, too:
Public Sub SpostaFile(sourceDirectory As String, ByVal destDirectory As String)
Dim from_date As DateTime = DateTime.Now.AddHours(-24)
Dim to_date As DateTime = DateTime.Now.AddHours(+24)
Dim folder As New DirectoryInfo(sourceDirectory)
Dim cp As Action(Of String) =
Sub(fileType)
Dim files = folder.EnumerateFiles(fileType).
Where(Function(fi) fi.CreationTime >= from_date AndAlso fi.CreationTime <= to_date AndAlso
fi.Name.Length >= 29 AndAlso fi.Name.Substring(22,7) = "inscriz" )
For Each file In xlsList
file.CopyTo(Path.Combine(destDirectory, file.Name))
Next
End Sub
Try
cp("*.PDF")
cp("*.XLS")
cp("*.XLSX")
cp("*.csv")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub