Directory.GetFiles - SearchOption.AllDirectories Does not give files in subfolders (vb) - vb.net

Directory.GetFiles - SearchOption.AllDirectories Does not give files that are located in subfolders. I'm trying to copy al .jpg files from a usb to the computer but when files are located in sub-folders, it does not copy them.
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
Dim sourceDir As String = ComboBoxUsbSelect.Text
Dim backupDir As String = FileDestination
Try
Dim picList As String() = Directory.GetFiles(sourceDir, "*.jpg", SearchOption.AllDirectories)
' Copy picture files.
For Each f As String In picList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
If delete = False Then
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
Else
File.Move(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName))
End If
Next
Catch dirNotFound As DirectoryNotFoundException
Console.WriteLine(dirNotFound.Message)
End Try
MessageBox.Show("Done!")
End Sub

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.

How to fix copied folder name

I have a vb application which copies folders and its subfolder that is working properly. My problem is that it is not copying the correct folder name of the folder being copied.
Like if I copy the folder with this location: C:\Users\Documents\Sample_Folder
The output copied folder name would be "Documents".
C:\Users\Documents\Sample_Folder\Sample_Folder_2
The output copied folder name would be "Sample_Folder".
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
Dim SourcePath As String = txtBrowse.Text
Dim DestinationPath As String = "C:\Users\1000258123\Desktop\NEW"
Dim newDirectory As String =
System.IO.Path.Combine(DestinationPath,
Path.GetFileName(Path.GetDirectoryName(SourcePath)))
If Not (Directory.Exists(newDirectory)) Then
Directory.CreateDirectory(newDirectory)
End If
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(SourcePath, newDirectory)
MsgBox("Copy Successful")
End Sub

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

Delete Many Files In Application Data Folder

I'm trying to delete 3 files (file1.sol file2.sol file3.sol)
from the Application Data folder. My code words just fine with one file, but how can I make it delete the three files?
Here is my code:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim path As String = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Dim fileList As New List(Of String)
GetAllAccessibleFiles(path, fileList)
Application.DoEvents()
Dim files As String() = fileList.ToArray
For Each s As String In fileList
My.Computer.FileSystem.DeleteFile(s)
Next
End Sub
Sub GetAllAccessibleFiles(ByVal path As String, ByVal filelist As List(Of String))
For Each file As String In Directory.GetFiles(path, "file1.sol")
filelist.Add(file)
Next
For Each file As String In Directory.GetFiles(path, "file2.sol")
filelist.Add(file)
Next
For Each file As String In Directory.GetFiles(path, "file3.sol")
filelist.Add(file)
Next
For Each dir As String In Directory.GetDirectories(path)
Try
GetAllAccessibleFiles(dir, filelist)
Catch ex As Exception
End Try
Next
End Sub
The first line in GetAllAccesibleFiles, is searching for files with the name: "file1.sol", that means it will only retrieve that file. Try "file*.sol" meaning it starts with "file" and ends with ".sol". That should work. If you only want to delete file1 ,2 ,and 3, not for example, file4, then you can run a for loop 3 times, check if "file1" exists, delete it, check if "file2" exists, and so on.

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)