Find a Directory somewhere in Subdirectories - vb.net

I want to find a directory somewhere among a lot of subdirectories using VB.NET. I have the path of the parent directory (D:\) and I have the name of the subdirectory (X) and I want to find this directory in any of the subdirectories of D:\. In D:\ I have 3 subdirectories (A, B, and C) and I want to find X (the name of the directory) inside A,BorC`. Is it possible to do that with VB.NET?

You can do so using the Directory.EnumerateDirectories method, like this:
For Each i As String In Directory.EnumerateDirectories("D:\", "X", SearchOption.AllDirectories)
Console.WriteLine("Matching Directory: " & i)
Next
Please note that there may be multiple matches. Also, be aware that if the directory tree is very large, it may take a long time for the method to find all of the matches. The key to that working for you is the SearchOption.AllDirectories option. By passing AllDirectories, that causes the method to search the entire directory tree below "D:\". If you omitted that parameter, or passed TopDirectoryOnly, it would only look at the directories that are directly children of "D:\". It would not search through all of the descendants.
If you just want to get an array of all the matching directories, you can alternatively use the Directory.GetDirectories method:
Dim matches() As String = Directory.GetDirectories("D:\", "X", SearchOption.AllDirectories)
If matches.Length > 0 Then
Console.WriteLine("First match: " & matches(0))
End If
The advantage of the EnumerateDirectories method, though, is that, if you only care about the first match, you can exit the loop after processing the first match and skip searching the rest of the directory tree. From the MSDN article:
The EnumerateDirectories and GetDirectories methods differ as follows: When you use EnumerateDirectories, you can start enumerating the collection of names before the whole collection is returned; when you use GetDirectories, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateDirectories can be more efficient.
For instance, if you really only cared about the first match, it would be more efficient to do this:
For Each i As String In Directory.EnumerateDirectories("D:\", "X", SearchOption.AllDirectories)
Console.WriteLine("First match: " & i)
Exit For
Next
Or with LINQ:
Dim firstMatch As String = Directory.EnumerateDirectories("D:\", "X", SearchOption.AllDirectories).FirstOrDefault()
If firstMatch IsNot Nothing Then
Console.WriteLine(firstMatch)
End If

Please check the below link
http://msdn.microsoft.com/en-us/library/6ff71z1w%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
it will help you in getting all the directories in the specified path. Regarding the second argument that is the "pattern" try and check pattern as "" and hopefully should return and array of all directories and subdirectories
Then you can just compare/search for the file name in the returned array list using simple for loop and display the result which will show where the file is located

Related

VB.NET file filter

I want get the oldest creation file in a directory but want to exclude the file ‘Startup’(Which is currently the oldest file). So I would like to skip that file and get the next oldest creation file in the directory which would be ‘TEST’.
This code only gets the Startup.
Dim oldestFile = folderlist.OrderBy(Function(fi) fi.CreationTime).First
1:
You use the Where function to filter.
Dim folder As New DirectoryInfo(folderPath)
Dim oldestFile = folder.EnumerateFiles().
Where(Function(fi) fi.Name <> "Startup.txt").
OrderBy(Function(fi) fi.CreationTime).
First()
Note that it is preferable to use EnumerateFiles rather than GetFiles unless you really want access to the full array of files after the fact. If you only need that one file, EnumerateFiles is better because it doesn't get all the files first and then perform the other operations on that array. You may already know this but most people don't at first.
Note also that I'm assuming that those are text files based on the icons. Change the name in the filter if they are something else. As a developer, you really ought to switch off the File Explorer feature that hides file extensions. That's for people who don't understand computers.

How do I add the file creation date filter?

How can I add the file creation date filter for files created today and tomorrow?
This part don't work and I need to add files created today and tomorrow:
.Where(Function(file) New FileInfo(file).CreationTime.Date = DateTime.Today.Date)
Dim pdfList As String() = _
Directory.GetFiles(sourceDir, "*.PDF").Where(Function(file) New
FileInfo(file).CreationTime.Date = _
DateTime.Today.Date)
For Each f As String In pdfList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length + 1)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, _
fName), True)
Next
Dim folder As New DirectoryInfo(sourceFolderPath)
Dim files = folder.EnumerateFiles("*.pdf")
.Where(Function(fi) fi.CreationTime.Date = Date.Today)
For Each file In files
file.CopyTo(Path.Combine(backupFolderPath, file.Name))
Next
There are a few things to note here:
We are creating a DirectoryInfo and using it to get FileInfo objects. Given that you were creating a FileInfo for each file anyway, it's silly not to do this. That FileInfo object gives you the creation time, file name without the folder path and a method to copy the file.
We are calling EnumerateFiles rather than GetFiles. The latter returns an array containing all files, but we don't want all files in this case. If you're going to filter then enumeration is better, because it gets each file one by one, processes a file and discards it before getting the next. That's more efficient. In this case, we don't even call ToArray or ToList, so the files aren't actually retrieved until the loop and then they are retrieved and processed one by one.
The is no point using Date.Today.Date. Today has already had the time zeroed. Internally, Date.Today uses Date.Now.Date.

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.

Visual Basic FileSystem.GetFiles

I'm making a console application and I want to see what files is in a folder
For Each foundFile As String In My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
Console.WriteLine(foundFile)
Next
after using this code and find that the folder is empty I need an If statement that say's
If foundfile has no files then
tell user no files found
end if
but I don't know how to write this so Visual Basic understands.
Load the files into a variable then check the count.
Dim files = My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
If files.Count = 0 Then
'tell user no files
Else
For Each file In files
Console.WriteLine(file)
Next
End If
FileSystem.GetFiles() returns a collection of file name strings. As OneFineDay showed, you can use the collection's Count property to know if any files were found.
The downside of using FileSystem.GetFile() is that it has to search the entire folder before then returning the entire list of filenames. If you are searching large folders and speed is an issue, consider using Directory.EnumerateFiles() instead. That way, you can output a message if no file was found, otherwise loop throuh the list of found files. For example:
Dim files = Directory.EnumerateFiles("c:\users\zac\desktop\booked vehicle\requested\").GetEnumerator()
If files.MoveNext Then
' files were found
Do
Console.WriteLine(files.Current)
Loop Until Not files.MoveNext
Else
' no files were found
End If
I personally would use Linq to accomplish this. It's very quick and efficient to use in this case. I put the Console.ReadLine() at the end to show the files, you can remove this if need to be. Also you can change the Console.WriteLine to not include the string (s) if you don't want to. The s was declared if you want to show the files and also to see if there are any files. As I said, this was for my viewing to see the files. Straight to the point!
Dim s As String = String.Join(Environment.NewLine, New DirectoryInfo("YOUR DIRECTORY").GetFiles().[Select](Function(file) file.Name).ToArray)
Console.WriteLine(If(s.Length > 0, s, "No files found!"))
Console.ReadLine()

Fastest subdirectory listing

I have an application where i want to get all subdirectories (first level) from a given path.
I use this code:
Dim di As New IO.DirectoryInfo(Application.StartupPath & "\Folderlist")
For Each d In di.EnumerateDirectories()
Console.WriteLine(d.ToString)
Next
As you can see, i just need the name of the folder, not some object with all info.
Is there any way i can speed this up?
Dim dirs() = Directory.GetDirectories(Application.StartupPath & "\Folderlist")
For Each dir In dirs
Dim parent = Path.GetFileName(dir)
Console.WriteLine(parent)
Next
MSDN -
Directory.GetDirectories
Gets the names of subdirectories (including their paths) in the
specified directory.
Path.GetFileName