Dir folder and subfolder shows result in one folder, but not other folder - vb.net

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

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.

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)

copy folder path to listbox

I manage to drag and drop multiple folder path to listbox, is it possible to do this using copy/paste, for example, you copy multiple folder on windows explorer then paste those folder path on the listbox using contextmenu, shortcut keys, or a button..
Private Sub lstFolder_DragDrop(sender As Object, e As Windows.Forms.DragEventArgs) Handles lstFolder.DragDrop
Dim directories As String() = DirectCast(e.Data.GetData(DataFormats.FileDrop), String())
For Each folder As String In From folders In directories Where Directory.Exists(folders)
If Not lstFolder.Items.Contains(folder.ToString()) Then
lstFolder.Items.Add(folder.ToString())
End If
Next
End Sub
Private Shared Sub lstFolder_DragEnter(sender As Object, e As Windows.Forms.DragEventArgs) Handles lstFolder.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
# Vignesh Kumar
works great, one question how about, copying the folder location from a document file or from address bar, here is my code so far.
Dim directories As String() = CType(Clipboard.GetData(Windows.Forms.DataFormats.FileDrop), String())
'loop through the string array, check if folder exist then adding each folder to the ListBox
For Each folder As String In From folders In directories Where Directory.Exists(folders)
If Not lstFolder.Items.Contains(folder.ToString()) Then
lstFolder.Items.Add(folder.ToString())
End If
Next
Yes. Use Clipboard object
string[] files = (string[])Clipboard.GetData(System.Windows.Forms.DataFormats.FileDrop);
Files or/and folders will be in this string array.

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.

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)