Files from sub directories - vb.net

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)

Related

Get all the folders and sub-folders and files in a directory Vb.Net

how can i get all the folders and sub-folders and files in a specific path directory?,
example:
+ folder1
- exe1
+ folder2
- exe1
- exe2
+ folder3
- exe1
+ folder2
- exe1
+ folder3
+ folder4
im using right now on:
Sub GetDirectories(ByVal StartPath As String)
For Each Dir As String In IO.Directory.GetDirectories(StartPath)
ListBox1.Items.Add(Dir)
ListBox1.Items.AddRange(IO.Directory.GetFiles(StartPath))
ListBox1.Items.AddRange(IO.Directory.GetFiles(Dir))
Next
End Sub
and:
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
For Each Dir As String In IO.Directory.GetDirectories(path)
GetDirectories(path)
Next
Next
but it not giving me all the files from the other sub-folders.
Edit:
using with listbox and i want see the full path when drop in the folder and after this giving all the sub folders and files
You can better use the TreeView to get more convenient results.
Simply get a TreeView from the ToolBox and use the following code for listing a specific directory and sub-directories (including files):
Private Enum ItemType
Drive
Folder
File
End Enum
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim node As TreeNode =
TreeView1.Nodes.Add("Hello") ' Specifying Folder Names
node.Tag = ItemType.Folder
node.Nodes.Add("FILLER")
End Sub
Private Sub file_view_tree_BeforeExpand(sender As Object, e As TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
Dim currentNode As TreeNode = e.Node
currentNode.Nodes.Clear()
Try
'Now go get all the files and folders
Dim fullPathString As String = currentNode.FullPath
'Handle each folder
For Each folderString As String In
Directory.GetDirectories(fullPathString)
Dim newNode As TreeNode =
currentNode.Nodes.Add(Path.GetFileName(folderString))
Dim x As String = Path.GetFileName("")
newNode.Tag = ItemType.File
newNode.Nodes.Add("FILLER")
Next
'Handle each file
For Each fileString As String In
Directory.GetFiles(fullPathString)
'Get just the file name portion (without the path) :
Dim newNode As TreeNode =
currentNode.Nodes.Add(Path.GetFileName(fileString))
newNode.Tag = ItemType.File
Next
Catch ex As Exception
End Try
End Sub
Note: I've modified this thread of Stack Overflow and customized as per of your requirement.

Dir folder and subfolder shows result in one folder, but not other folder

Just trying to learn VB.net.
Making something that lists all files an folders in folder and subfolder.
Got a testfolder in root C:\ with a 2 subfolders and som files in al folders.
On execution listbox is filled with al files an folders including subfolders an files in subfolders.
But..
If id choose a folder on G:\ things get strange, and I only get A few folders or files listed
This is my first question here,so if if screw up in telling you, I am sorry
Public Class Form1
Dim R As IO.StreamReader
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Me.FolderBrowserDialog1.ShowDialog()
Listfiles(Me.FolderBrowserDialog1.SelectedPath)
End Sub
Public Sub Listfiles(ByVal Pad As String)
Dim DirInfo As New IO.DirectoryInfo(Pad)
Dim FileObject As IO.FileSystemInfo
Dim strBESTAND As String
For Each FileObject In DirInfo.GetFileSystemInfos
'if FileObject is a folder
If FileObject.Attributes = IO.FileAttributes.Directory Then '
Listfiles(FileObject.FullName)
Me.ListBox1.Items.Add(FileObject.FullName)
Else
strBESTAND = (FileObject.FullName)
Dim information = My.Computer.FileSystem.GetFileInfo(strBESTAND)
' If extention matches ..........
Dim strEXTENTIE As String
'if extentie is tikt in checkedlistbox
For i As Integer = 0 To (CheckedListBoxEXTENTIES.CheckedItems.Count - 1) ' iterate on checked items
'only us ticked items
strEXTENTIE = ((CheckedListBoxEXTENTIES.GetItemText(CheckedListBoxEXTENTIES.CheckedItems(i)).ToString))
If information.Extension = "." & strEXTENTIE Then
strBESTAND = information.Name
Me.ListBox1.Items.Add(FileObject.Name)
End If
Next
End If
Next
MessageBox.Show("Done!")
End Sub
The string comparisons are case sensitive by default. You will miss extensions having another case as in the CheckedListBox. Use
If String.Compare(information.Extension, "." & strEXTENTIE, _
StringComparison.OrdinalIgnoreCase) = 0 Then
But it would be more efficient if you prepared the extensions before browsing the folders
'Outside of subroutines
Dim extensions As New HashSet(Of String)()
'In Button1_Click before calling Listfiles
For i As Integer = 0 To CheckedListBoxEXTENTIES.CheckedItems.Count - 1
extensions.Add("." & _
CheckedListBoxEXTENTIES.CheckedItems(i).ToString().ToLowerInvariant())
Next
Then you can check the extensions like this, without having to loop through the CheckedListBox for each file.
If extensions.Contains(information.Extension.ToLowerInvariant()) Then

Adding sub folders and files to menu strip

Basically, I'm trying to populate a menu strip with a list of directories from a static location and then nested any sub directories underneath its parent and then display the files in the folder
I've got the basic
Dim loc As String = "C:\test\"
For Each dirs As String In Directory.GetDirectories(loc)
Dim dirinfo As New DirectoryInfo(dirs)
p1.DropDownItems.Add(dirinfo.Name)
Next
Which gives me the first line of directories but just not to sure where to go from here. Ultimately I would then like to be able to open the files form here.
Can anyone point me in the right direction
Thanks
This works for me, though it seems to only go four levels deep
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' assuming you have a single top level menu item named p1
Dim loc As String = "C:\test\"
AddSubDirsToMenuRecursive(p1, loc)
End Sub
Private Sub AddSubDirsToMenuRecursive(m As ToolStripMenuItem, d As String)
Dim dirs = Directory.GetDirectories(d)
For Each dir As String In dirs
Dim dirinfo As New DirectoryInfo(dir)
Dim mi As New ToolStripMenuItem(dirinfo.Name)
m.DropDownItems.Add(mi)
m.DropDownItems.AddRange(
dirinfo.GetFiles.Select(Of ToolStripMenuItem) _
(
Function(fi As FileInfo) New ToolStripMenuItem(fi.Name)
).ToArray())
AddSubDirsToMenuRecursive(mi, dirinfo.FullName)
Next
End Sub
If you are interested in opening the file when clicking it, replace the m.DropDownItems.AddRange block with this
m.DropDownItems.AddRange(
dirinfo.GetFiles.Select(Of ToolStripMenuItem) _
(Function(fi As FileInfo)
Dim mi1 = New ToolStripMenuItem(fi.Name)
AddHandler mi1.Click,
Sub(sender As Object, e As EventArgs)
Process.Start(fi.FullName)
End Sub
Return mi1
End Function
).ToArray())

Copying files back to a Specific Folder

This program extracts files from a folder that has been modified today, and after the files are placed into another folder a batch file then deletes the rest of the non-modified files in that source folder.
The last thing my program is supposed to do is copy files from separate folder, and place them back into that source folder.
But my program only extracts the modified files, deletes the rest of the files in that folder, but when I run the program to also copy and place the new files into the source folder it just doesn't do it. Does anyone know why?
Imports System.IO
Public Class frmExtractionator
' Dim txtFiles1 As Control
Dim sourceDirectory As String = "F:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "F:\FilesExtracted"
Dim originalDirectory As String = "F:\OriginalTestFiles"
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
If (IO.File.GetLastWriteTime(currentFileLoc).ToString("MM/dd/yyyy") = DateTime.Now.ToString("MM/dd/yyyy")) Then
MessageBox.Show(currentFileLoc & " moved", "Moved Succesfully")
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
System.Diagnostics.Process.Start("F:\poop.bat")
Try
Dim txtFiles2 = Directory.EnumerateFiles(originalDirectory)
For Each currentFileLoc2 As String In txtFiles2
Dim fileName = currentFileLoc2.Substring(originalDirectory.Length + 1)
File.Move(currentFileLoc2, Path.Combine(sourceDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class
Change
Dim fileName = currentFileLoc2.Substring(originalDirectory.Length + 1)
to
Dim FileName = IO.Path.GetFileName(currentFileLoc2)

How to correctly enumerate files in selected path?

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.