Search multiple files though sub folders VB.net - vb.net

I'm having a hard time trying to figure it out how to find multiple files through sub folders, I'm looking for different file names and I think that's why I can't solve it.
"file_name" in the code is the name of the varible, I pull the name of the document from the data base which it's stored in a field without the extension and then when it finds the .docx/doc file it should convert it to pdf.
Dim di As DirectoryInfo = New DirectoryInfo("\\192.168.1.70\sisint\court\
agreements")
For Each fi In di.GetFiles(file_name, SearchOption.AllDirectories)
'seleccionamos los archivos con las extensiones de Word
If fi.Extension.ToUpper = ".DOC" Or fi.Extension.ToUpper = ".DOCX" Then
ListaArchivos.Add(fi.FullName)
ListaNombres.Add((fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length)))
End If
Next

To search a directory with multiple sub directories for a file you can use the following line of code:
Dim folders As List(Of String) = New DirectoryInfo("C:\Test").EnumerateFiles("test.txt", SearchOption.AllDirectories).[Select](Function(d) d.FullName).ToList()
Replace "C:\Test" with the directory to search and "test.txt" with the filename to search for. If the same file name is in multiple directories all iles matching that name will be returned.
To find multiple file names, just loop through your list(file_name) replacing "test.txt" with the file. How you save all the output is up to you. You can add everything found to 1 large list and then convert them all to pdf's, or you can convert them as you find them.
Here is an example:
Private Function FindFiles() As List(Of String)
Dim allFilesFound As New List(Of String)
Dim dirSearch = "C:\Test"
Dim file_name As New List(Of String) From {"test.txt", "test2.txt"}
For Each file In file_name
allFilesFound.AddRange(New DirectoryInfo(dirSearch).EnumerateFiles(file, SearchOption.AllDirectories).[Select](Function(d) d.FullName).ToList())
Next
Return allFilesFound
End Function
Keep in mind that the more files in file_name and the farther up the Directory tree you start searching from, the longer this will take. If you are dealing with large amounts of files, then consider using recursion so you can find all files in one pass. You can take a look here Recursively search folder with subdirectories in .NET and modify the code demonstrated there to fit your search pattern.

Related

VB: Search files in a folder and show only Word and PDF files

I have problem searching folder and find all files with specific name.
With this method I am able to browse my folder and find all files. But only Word files.
Dim fi As FileInfo() = path.GetFiles(fileName & "*.doc*", SearchOption.AllDirectories)
Now I would like to search Word and PDF. Is there a way how I can find it?
If I just write a dot instead of .doc it searches the folder but finds all files. Excel, txt etc.
Dim fi As FileInfo() = path.GetFiles(fileName & "*.*", SearchOption.AllDirectories)
The goal would be to find only certain types of files.
It is not possible to use the GetFiles method to enumerate files with multiple extensions. To do that, you'll have to write your own code to do the filtering. I also recommend you use the EnumerateFiles method as it provides better performance over the GetFiles method in most cases.
Here is sample code to do the filtering as you require
Dim filterExtensions = {".docx", ".pdf"}
Dim files = From f In System.IO.Directory.EnumerateFiles("C:\Path", "*.*", _
SearchOption.AllDirectories)
Let fi = New FileInfo(f)
Where filterExtensions.Contains(fi.Extension.ToLower())
Select fi

How to get a filename without using for next

Using VB.Net
Get a file name without using for next from the directory
Dim filefound = Directory.GetFiles("C:\", "1.txt")
For Each inwardfile In filefound
Dim strFilename As String = Path.GetFileName(inwardfile)
Next
The above code is working fine, but i dont want to use for loop because i will always get one file at a time not the list of files also i am searching with filename not like "*.txt"
So How to modify the code, Any one can assist.
Your question is inconsistent which makes it very unclear. Do you want a file name or a collection of them? If you want filename not like "*.txt" then why use "1.txt" for GetFiles?
This will answer the title question How to get a filename without using for next. For this, assume a directory full of ".json" files. Some are named cs###.json (e.g. cs001.json) some are named vb###.json and many others.
Path would work to allow you to examine parts of the filename, but DirectoryInfo will provide access to some of that info via FileInfo objects. This uses EnumerateFiles to be able to filter out unwanted files so they are not even returned to your code/array variable.
Dim dix As New DirectoryInfo("C:\Temp\Json")
Get the json files which DO NOT start with CS. This will return an array of FileInfo objects in case you need to do further exclusions:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.StartsWith("cs") = False).
ToArray()
Get the json files which ARE "*1.json" and DO NOT start with "cs". In this case, the last Select method will cause an array of filenames to be returned:
Dim jFile = dix.EnumerateFiles.Where(Function(f) f.Extension = ".json" AndAlso
f.Name.EndsWith("1.json") AndAlso
f.Name.StartsWith("cs") = False).
Select(Function(q) q.Name).
ToArray()
Change the Select to 'Function(q) q.FullName` if you want the full path name. These should come close to whatever you are really looking for.

Zip multiple files to one folder

So I am having trouble trying to reconcile this concept as every change I do doesn't seem to fix the issue.
I have multiline textbox and can enter multiple values separated by commas and here are the details:
Each value represents a folder
And each folder has multiple documents/other folders inside
All of these values are in one main directory (lets call it folder path)
For example say I enter in my textbox "65635,65636" each of those represent a folder in the directory i.e. "\folderpath\65635" and "\folderpath\65636", I am trying to zip these whole folders via DotNetZiplib, I know how to do this if I specifically reference one folder but is there anywhere to loop through the textbox to get the names of the folders and have the files added to one zipped folder?
Using zip As New ZipFile = new ZipFile
Dim files() As String = Directory.GetFiles(folderpath & textboxvalue)
For each textboxvalue in directory.getfiles
zip.Addfile(textboxvalue)
The zipfile function I have would know to loop through these as opposed to assuming it's one big file.
You must split textbox values in array first to get numbers separated by comma. Next you will need Combine your folder with this splited text values, creating path correctly.
Check if folder exists in system if Yes then get all files from Directory and for each filename zip it.
Something like this:
Using zip As New ZipFile("your zip filename")
For Each str As String In textboxvalue.Split(",")
Dim path as String = System.IO.Path.Combine(folderpath, str)
If System.IO.Directory.Exists(path) = False Then
Continue For
End If
Dim files() As String = Directory.GetFiles(path)
For Each fileName As String In files
zip.Addfile(fileName)
Next
Next
End Using

Read File name and put it into Variable

I am trying to find a way to read a specific file name in a directory and then put the file name into a variable. In my program I have a batch file that zips a folder called logs and then changes the name of zip to username_date_time.zip.
So basically if the filename was jobs_03152015_1315.zip I would want the entire file name but not the path stored into a variable. The file starts off on the user's local machine. It is then uploaded into a network share.
The network path will be uploaded to a database for others to view. I want to just add the unique file name to the end of a pre set path. Here is the code I am using.
Dim filePath As String = "c:\temp\logs\"
If (System.IO.Directory.Exists(filePath)) Then
For Each file As String In filePath
If file.Contains(".zip") Then
Dim zip As String = file
testbox.Text = zip
Exit For
End If
Next
End If
You can enumerate all files using the GetFiles() method of the static (shared in VB) Directory class, see msdn.
Assuming you have more then 1 file I add the files to a listbox control. But you could change that if you wish. I get the filename using the Path class. You will find a lot other helpful functions in this class.
Dim searchPath = "C:\temp\logs"
Dim files = Directory.GetFiles(path, "*.zip")
For Each file In files
listbox1.Items.Add(path.GetFileName(file))
Next
This should do it.
Your loop doesn't read anything. The string variable filePath is just the name of the directory, not a list of the files in that directory. Calling For Each over a string simply enumerates each character contained in the string
To get a list of files contained in that folder you need Directory.EnumerateFiles() and pass the filePath variable and the extension required.
It seems that you are interested only to find if that folder contains at least one file with zip extension. If this is the case then you could remove the explicit loop and write simply
Dim file = Directory.EnumerateFiles(filePath, "*.zip").FirstOrDefault()
If file IsNot Nothing Then
testbox.Text = Path.GetFileName(file)
End If
Using Path.GetFileName will return just the file without the path part
Try this code :
Dim FilePath As String = "c:\temp\logs\"
If (System.IO.Directory.Exists(FilePath)) Then
For Each File As String In System.IO.Directory.EnumerateFiles(FilePath)
If File.Contains(".zip") Then
Dim info As New System.IO.FileInfo(File)
zip = info.Name
testbox.Text = zip
Exit For
End If
Next
End If

Populate ComboBox with Each FileType From Directory

Basically, I have a ComboBox which I want to populate with File Extensions from a specific Directory.
Currently, I'm using:
Dim dir = "C:\"
For Each file As String In System.IO.Directory.GetFiles(dir)
cmb_FileTypes.Items.Add(System.IO.Path.GetExtension(file))
Next
This doesn't work properly because it basically loads all the extensions for all the files in the directory. I want it so that it shows each ONE file type. for instance, if there are 10 files:
File1.jpg
File2.jpg
File3.png
File4.mp3
File5.mp3
File6.dat
File7.dat
File8.tif
File9.jpg
File10.mp3
Out of these 10 Files, there are 6 file extensions that are different file extensions:
Jpg
Png
Mp3
Dat
tif
How do I load each 1 one these file extensions into the ComboBox rather than just repeating it?
Use LINQ to add all the extensions to the combobox in one bulk.
cmb_FileTypes.Items.AddRange((From name In Directory.GetFiles(dir) Select Path.GetExtension(name).Replace(".", "") Distinct).ToArray())
You could use LINQ to group the extensions
For Each file As String In Directory.GetFiles(dir).[Select](Function(p) Path.GetExtension(p)).Distinct().OrderBy(Function(p) p).ToList()
cmb_FileTypes.Items.Add(System.IO.Path.GetExtension(file))
Next
or you can create a method which returns a List<string> containing unique extensions.
Public Function UniqueExtensions(filenames As String()) As List(Of String)
Dim extSet As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
For Each file As String In filenames
extSet.Add(System.IO.Path.GetExtension(file))
Next
Return extSet.ToList()
End Function