How to correctly enumerate files in selected path? - vb.net

Visual Studio 2008 (vb.net)
I made simple anivirus but when I make Full scan by this code:
FolderBrowserDialog1.SelectedPath = ("C:\")
'first scan:************************************
Try
For Each strDir As String In
System.IO.Directory.GetDirectories(FolderBrowserDialog1.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
ListBox1.Items.Add(strFile)
Next
Next
'Start the timer:
Catch ex As Exception
End Try
Timer1.Start()`
Just scan the first 6 files ...
I think the problem from Windows Folder permissions (Windows - Program Files ...etc)
So how to fix it?

Put a Console.WriteLine(ex) in your catch block so you can see any exceptions that are thrown. You'll probably see your problem then. Most likely permissions.

You could try the following:
For Each strFile As String In System.IO.Directory.GetFiles(strDir, "*", IO.SearchOption.AllDirectories)
Edit:
You could try the last solution found in this thread:
http://www.vbforums.com/showthread.php?t=624969
I tried this myself and it was super slow, but worked fine.
Public Class Form1
Private Sub foo(ByVal aDir As String)
Try
Dim di As New IO.DirectoryInfo(aDir)
Dim aryFiles() As IO.FileInfo = di.GetFiles("*.*")
Dim aryDirs() As IO.DirectoryInfo = di.GetDirectories()
For Each fi As IO.FileInfo In aryFiles
rslts.Add(fi.FullName)
Next
For Each d As IO.DirectoryInfo In aryDirs
foo(d.FullName)
Next
Catch ex As Exception
'Stop 'the catch should be more specific
End Try
End Sub
Dim rslts As List(Of String)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
rslts = New List(Of String)
foo("C:\")
ListBox1.Items.Clear()
ListBox1.Items.AddRange(rslts.ToArray)
End Sub
End Class
It looks like your solution essentially loops through the first folder it can find and stops there. This solution is a bit different as it will recursively go through all the files and folders based on the start location.

Related

Searching all jpg's from all drives in a computer vb.net

I want to list all JPG files from all drives in a computer with there full path.
So I tried following code but it only list few random files, it wont search all files. i got this from here: Searching a drive with vb.net
Public Sub DirSearch(ByVal sDir As String)
Dim fl As String
Try
For Each dir As String In Directory.GetDirectories(sDir)
For Each fl In Directory.GetFiles(dir, "*.jpg")
listbox1.Items.Add(fl)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
'form1 load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DirSearch("c:\")
DirSearch("d:\")
DirSearch("e:\")
DirSearch("f:\")
DirSearch("g:\")
DirSearch("h:\")
DirSearch("i:\")
DirSearch("j:\")
DirSearch("k:\")
'DirSearch("so on.....")
savetxtfile()
End Sub
Save searched result to text file in system drive
Sub savetxtfile()
Dim systemdrv As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
TextBox1.Text = listbox1.Items.Count
Dim w As IO.StreamWriter
Dim r As IO.StreamReader
Dim i As Integer
w = New IO.StreamWriter(systemdrv + "temp\test.txt")
For i = 0 To listbox1.Items.Count - 1
w.WriteLine(listbox1.Items.Item(i))
Next
w.Close()
End Sub
You're ignoring your exception...
Debug.WriteLine(ex.Message)
Use this instead (so you can't miss it for debugging)...
MessageBox.Show(ex.Message)
Knowing that what's happening is probably a folder access error, you need to handle that accordingly.
For Each dir As String In Directory.GetDirectories(sDir)
Try
For Each fl In Directory.GetFiles(dir, "*.jpg")
lstbxTest.Items.Add(fl)
Next
Catch ex As Exception
Continue For
End Try
Next
Effectively, continue if you get an error, because you don't really care in this case.
You might want to add some exceptions in there (If dir = "whatever" Then Continue For) so you're not trying to go through every single system folder in operating system.

Files from sub directories

Can somebody help me to implement to add files from sub directories to my listbox ? I have looked for some information from google, but source code from those examples was really diffrent than my and I'm newbie in VB.NET. I think it may be the System.IO.SearchOption.AllDirectories but I have no clue how to implement it in my code.
Private Sub ButtonFolder_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFolder.Click
FolderBrowserDialog1.ShowDialog()
FilePathLabel.Text = System.IO.Path.GetFileName(FolderBrowserDialog1.SelectedPath)
Dim folder As New IO.DirectoryInfo(System.IO.Path.GetFullPath(FolderBrowserDialog1.SelectedPath))
Dim arrfile() As IO.FileInfo
Dim file As IO.FileInfo
arrfile = folder.GetFiles("*.*")
dicPaths.Clear()
For Each file In arrfile
'ListBox1.Items.Add(file.FullName)
dicPaths.Add(file.Name, file.FullName)
Next file
For Each item As String In dicPaths.Keys
ListBox1.Items.Add(item)
Next item
Label1.Text = "Total Items : " + ListBox1.Items.Count.ToString
End Sub
Try This:
Public Function FindFiles(ByVal Path As String) As Boolean
Dim Directories As New IO.DirectoryInfo(Path)
Dim Directory As IO.DirectoryInfo
Dim File As IO.FileInfo
For Each Directory In Directories.GetDirectories
For Each File In Directory.GetFiles
ListBox1.Items.Add(File.Name)
Next
If Directory.GetDirectories.Length > 0 Then
FindFiles(Directory.FullName)
End If
Next
End Function
Usage: FindFiles(FolderBrowserDialog1.SelectedPath)

Display all drives, files, and subfolders in treeview

I'm looking for the simplest way to display all drives, files, and subfolders in a treeview. If someone's got a snippet of code to do this that they don't mind sharing I would really appreciate it.
The closest I've gotten was this code I tried using, but it gave me a "IOException was unhandled" error saying "The device is not ready." error at runtime (after about 5-10 sec) on the line below
Dim folders() As String = IO.Directory.GetDirectories(dir)
underneath is the rest of the code
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim drives As System.Collections.ObjectModel.ReadOnlyCollection(Of IO.DriveInfo) = My.Computer.FileSystem.Drives
Dim rootDir As String = String.Empty
For i As Integer = 0 To drives.Count - 1
rootDir = drives(i).Name
TreeView1.Nodes.Add(rootDir)
PopulateTreeView(rootDir, TreeView1.Nodes(i))
Next
End Sub
Private Sub PopulateTreeView(ByVal dir As String, ByVal parentNode As TreeNode)
Dim folder As String = String.Empty
Try
Dim folders() As String = IO.Directory.GetDirectories(dir)
If folders.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each folder In folders
childNode = New TreeNode(folder)
parentNode.Nodes.Add(childNode)
PopulateTreeView(folder, childNode)
Next
End If
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add(folder & ": Access Denied")
End Try
End Sub
Seems like you're off to a good start. The IOException you receive is most likely caused by your procedure trying to list contents on an empty disc drive, which is obviously impossible.
The fix is simple:
For i As Integer = 0 To drives.Count - 1
If Not drives(i).IsReady Then
Continue For
End If
rootDir = drives(i).Name
TreeView1.Nodes.Add(rootDir)
PopulateTreeView(rootDir, TreeView1.Nodes(i))
Next
Besides that, I recommend not loading folder contents until a node is clicked. Limit the recursive call to 1 level (current directory + content of all its subdirectories). That way, you get the best performance while still being able to determine whether a subdirectory should have the treeview expand button.

Searching a drive with vb.net

I am making a program that searches your drive for an executable.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim di As New DirectoryInfo("C:\")
Dim files() As FileInfo
Dim a As Integer
Do While a = 0
Try
files = di.GetFiles("FileName.exe", SearchOption.AllDirectories)
Catch ex As UnauthorizedAccessException
End Try
If Not files Is Nothing Then
a = 1
End If
Loop
txt_Location.Text = files(0).FullName
End Sub
As soon as it hits the first UnauthorizedAccessException, it gets stuck in an infinite loop. How do I skip over the files that produce the exception?
EDIT:
This is what I have now:
Public Sub DirSearch(ByVal sDir As String)
Dim dir As String
Try
For Each dir In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "Filename.exe")
ComboBox1.Items.Add(file)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
DirSearch("C:\")
End Sub
You need recursion here which handles each folder.
EDIT: As requested by the OP, a little example:
Public Sub DirSearch(ByVal sDir As String)
Try
For Each dir as String In Directory.GetDirectories(sDir)
For Each file In Directory.GetFiles(dir, "yourfilename.exe")
lstFilesFound.Items.Add(file)
Next
DirSearch(dir)
Next
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
End Sub
Also take a look at the following answers:
Looping through all directory's on the hard drive (VB.NET)
How to handle UnauthorizedAccessException when attempting to add files from location without permissions (C#)
Also note, if you have enough access rights, you could simplify your code to this:
Dim di as New DirectoryInfo()
Dim files = di.GetFiles("iexplore.exe", SearchOption.AllDirectories) 'already returns all files at once
And at last but not least:
Avoid having infinite loops. Like in your example, they can lead to broken code just because some circumstances aren't like you've expected them to be. Imagine your code has run on your PC and you deployed this software to a customer - horrible scenario. ;-)

Does anyone have a WORKING example that displays a directory tree structure in a TreeView for VB .NET?

I have looked everywhere and cannot find a version that works. The ones I found are all either outdated or have errors.
I have something that is working for the most part, but I'm having some trouble with restricted-access folders.
The code I'm using is as follows:
Imports System.IO
Public Class frmMain
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each drive In DriveInfo.GetDrives
Dim i As Integer = TreeView1.Nodes.Count
TreeView1.Nodes.Add(drive.ToString)
If drive.IsReady Then
PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
Next
End Sub
Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
Dim directory As New DirectoryInfo(sDir)
Try
For Each d As DirectoryInfo In directory.GetDirectories
Dim t As New TreeNode(d.Name)
PopulateTree(d.FullName, t)
node.Nodes.Add(t)
Next
Catch excpt As UnauthorizedAccessException
Debug.WriteLine(excpt.Message)
End Try
End Sub
End Class
For testing purposes I replaced this section...
If drive.IsReady Then
PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
...with this...
If drive.toString = "L:\"
PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
...and it worked fine for that drive. The L:\ is a removable USB drive by the way.
However, with the original code I get debug errors on some folders because they are access-restricted. Is there any way to ignore those particular folders and show the rest?
Yes, you need to tighten the scope of your try catch block. You are catching the error too far away from where it occurs. Try this:
Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
Dim directory As New DirectoryInfo(sDir)
For Each d As DirectoryInfo In directory.GetDirectories
Dim t As New TreeNode(d.Name)
Try
PopulateTree(d.FullName, t)
node.Nodes.Add(t)
Catch excpt As UnauthorizedAccessException
Debug.WriteLine(excpt.Message)
EndTry
Next
End Sub