How to fix copied folder name - vb.net

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

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.

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

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

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.

Creating an application that moves a collection files from one place to another using VB

So this is an application I have to create that moves files from one directory to another, both directories being specified by the user. It seems easy enough, but the problem is that there are millions of files that have to be searched through. These files are all named with 8 digits for example, "98938495.crt". The directory where all these files are has multiple folders. These folders within the main one are named with the first two digits of all the files that are in the folder. And then in that folder there are roughly ten zipped folders that contain 100,000 files each. The name of those folders are the minimum and maximum names of the files. For example, I go into the main folder, then click on the "90xx" folder. In that one there are 10 zipped folders which are named with the minimum and maximum names of the files, like "90000000_90099999.zip". That zip folder contains 100000 files. Now, this app is supposed to find all the files that the user inputs and then move them to a folder specified by the user. I have posted my code so far below, any help at all is greatly appreciate!!
FYI: The STID is the name of the file.
GUI for the app
Edit: I realized there is no way to answer this question because there really isn't a question, just a broken app. Basically, how do i search for the items in the directory and then copy them into a new directory?
Imports System
Imports System.IO
Public Class CertFinder
Private Sub SourceDirectoryTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SourceDirectoryTB.TextChanged
End Sub
Private Sub DestinationDirectoryTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DestinationDirectoryTB.TextChanged
End Sub
Private Sub SearchTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchTB.TextChanged
End Sub
Private Sub SourceButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SourceButton.Click
Dim fbd As New FolderBrowserDialog
fbd.RootFolder = Environment.SpecialFolder.MyComputer
If fbd.ShowDialog = DialogResult.OK Then
SourceDirectoryTB.Text = fbd.SelectedPath
End If
End Sub
Private Sub DestinationButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DestinationButton.Click
Dim fbd As New FolderBrowserDialog
fbd.RootFolder = Environment.SpecialFolder.MyComputer
If fbd.ShowDialog = DialogResult.OK Then
DestinationDirectoryTB.Text = fbd.SelectedPath
End If
End Sub
Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchButton.Click
'Array of stids
Dim stidsToFind As String()
'get text in the searchTB textbox
Dim searchTBText As String = Me.SearchTB.Text.Trim()
'splits stids into seperate lines
stidsToFind = searchTBText.Split(vbCrLf)
'gets text from source directory text box
Dim sourceDirectory As String = Me.SourceDirectoryTB.Text.Trim()
'gets text from destination directory text box
Dim destinationDirectory As String = Me.DestinationDirectoryTB.Text.Trim()
Dim fullPathToFile As String = sourceDirectory
'Go through each stid in the search text box and continue if nothing
For Each stidToFind As String In stidsToFind
If String.IsNullOrWhiteSpace(stidToFind) Then
Continue For
End If
'Find the first two digits of the stid
Dim firstTwoDigitsOfSTID As String = stidToFind.Substring(0, 2)
'In the specified directory, find the folder with the first two digits and "xx"
fullPathToFile = fullPathToFile & "\" & firstTwoDigitsOfSTID & "xx"
Dim allFileNames As String() = Nothing
allFileNames = Directory.GetFiles(sourceDirectory, "*.crt*", SearchOption.AllDirectories)
Next
'-------------------------------------------------------------------------------
Try
If File.Exists(fullPathToFile) = False Then
Dim FS As FileStream = File.Create(fullPathToFile)
FS.Close()
End If
File.Move(fullPathToFile, destinationDirectory)
Console.WriteLine("{0} moved to {1}", fullPathToFile, destinationDirectory)
Catch ex As Exception
MessageBox.Show("File does not exist")
End Try
Dim sc As New Shell32.Shell()
'Declare the folder where the files will be extracted
Dim output As Shell32.Folder = sc.NameSpace(destinationDirectory)
'Declare your input zip file as folder .
Dim input As Shell32.Folder = sc.NameSpace(stidsToFind)
'Extract the files from the zip file using the CopyHere command .
output.CopyHere(input.Items, 4)
'-------------------------------------------------------------------------------
' 1. Get the names of each .zip file in the folder.
' 2. Assume that the .zip files are named as such <minimum STID>_<maximum STID>.zip
' 3. For each .zip file name, get the Minimum STID and Maximum STID values.
' 4. Check the range of 'stidToFind' against the STID ranges of each .zip file.
' 5. Once the .zip file is located,
' a. Copy the .zip file to the local computer OR
' b. Just leave it where it is.
' 6. Unzip the file.
' 7. Create the full file name path. ../<stidToFind>.crt
' 8. Copy the file to the destination directory.
' 9. Delete the unzipped folder
' 10. Delete the .zip file (IF you've copied it to your local computer).
End Sub
End Class
In answer to the .ZIP unpacking, use the System.IO.Packaging (more can be found at CodeProject - Zip Files Easy)
Don't you think using a database would be easier to store that data?

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)