VB.NET - Choose folder by browsing and copy file from application directory - vb.net

Hello StackOverflow users. I am trying to create an application where you can browse to a folder, press install button and it will copy some files to the directory of your choosing?
I found some example code but
how do i go on with my code from here? Cant figure out how to copy the files. You can see at last in the code i tried to copy files but its not really working, how do i use the function? I want the files to come from the application directory. And copy to the browsed folder.
Public Class Installer
Private Sub Installer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
End Sub
Private Sub BrowseButton_Click_1(sender As System.Object, e As System.EventArgs) Handles BrowseButton.Click
' Declare a variable named theFolderBrowser of type FolderBrowserDialog.
Dim theFolderBrowser As New FolderBrowserDialog
' Set theFolderBrowser object's Description property to
' give the user instructions.
theFolderBrowser.Description = "Please browse to your GTAIV directory."
' Set theFolderBrowser object's ShowNewFolder property to false when
' the a FolderBrowserDialog is to be used only for selecting an existing folder.
theFolderBrowser.ShowNewFolderButton = False
' Optionally set the RootFolder and SelectedPath properties to
' control which folder will be selected when browsing begings
' and to make it the selected folder.
' For this example start browsing in the Desktop folder.
theFolderBrowser.RootFolder = System.Environment.SpecialFolder.Desktop
' Default theFolderBrowserDialog object's SelectedPath property to the path to the Desktop folder.
theFolderBrowser.SelectedPath = My.Computer.FileSystem.SpecialDirectories.Desktop
' If the user clicks theFolderBrowser's OK button..
If theFolderBrowser.ShowDialog = Windows.Forms.DialogResult.OK Then
' Set the FolderChoiceTextBox's Text to theFolderBrowserDialog's
' SelectedPath property.
Me.FolderTextBox.Text = theFolderBrowser.SelectedPath
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles InstallButton.Click
My.Computer.FileSystem.CopyFile(My.Application.Info.DirectoryPath, theFolderBrowser.SelectedPath)
End Sub
End Class
SnoX

When you call this line of code
My.Computer.FileSystem.CopyFile(My.Application.Info.DirectoryPath, _
theFolderBrowser.SelectedPath)
the theFolderBrowser object cannot be referenced because it was a local variable inside another method. However, before exiting, you have copied the selected path into a textbox. You could use that textbox as destination of your copy
My.Computer.FileSystem.CopyDirectory(My.Application.Info.DirectoryPath, _
Me.FolderTextBox.Text )
And also keep in mind that CopyFile copies only one file, if you intend to copy an entire folder you need the CopyDirectory method. There is another important detail in this method:
If your files exist in the destination directory and you don't use the overload with the overwrite flag you will get an exception
My.Computer.FileSystem.CopyDirectory(My.Application.Info.DirectoryPath, _
Me.FolderTextBox.Text, True )

Related

Why Is A FilePath Item With ~$ Added To ListBox

I am adding file paths from a folder to a List Box which are then opened as text in a Rich Text Box. I have used the same syntax as the code below for achieving the same purpose in another List Box and it works just fine. But, in the current example, I have two files in the default MyProjects folder (i.e. default folder is created by my app), but when I add the file paths from the folder as items to the List Box, I get a third item with ~$ in the file path? This item is obviously some kind of repetition of the first file path in the list? The two files in the default folder are also created by my app so, if this is a file access issue, I don't understand why I wouldn't have access to a file created by my app? Can anyone give me a clue what's happening here?
What I have Tried:
I have tried debugging to check where the extra file path is coming from. As far as I can tell, it is being created when I add the file paths to the List Box? i.e. commenting out the code for adding the items to the List Box stops all items being added, but doesn't tell me where this extra item is coming from?
The "Extra Item" Issue:
System.Windows.Forms.ListBox+ObjectCollectionC:\Users\username\Documents\MySolution\MyProjects\RTFdoc.rtf
C:\Users\username\Documents\MySolution\MyProjects\Testdoc.rtf
C:\Users\username\Documents\MySolution\MyProjects~$Fdoc.rtf
The Code:
lbxName.Items.AddRange(Directory.GetFiles("C:\Users\" + username + "\Documents\MySolution\MyProjects"))
lbxName.SelectedIndex = 0
Code For Loading:
For Each item In lbxName.SelectedItems
RTB.LoadFile(lbxName.SelectedItem, RichTextBoxStreamType.RichText)
Next
I cannot reproduce the error in the following code.
Private Sub FillListBox()
ListBox1.Items.AddRange(Directory.GetFiles("C:\Users\" & username & "\Documents\MySolution\MyProjects"))
ListBox1.SelectedIndex = 0
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillListBox()
End Sub
Please read the comments in the following code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each item In ListBox1.SelectedItems
'The following will overwrite the contents of the RichTextBox on each iteration
'This overload of LoadFile will only handle .rtf files
RichTextBox1.LoadFile(item.ToString)
Next
End Sub
I suggest you set the SelectionMode property to One in the designer and do the following.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
RichTextBox1.LoadFile(ListBox1.SelectedItem.ToString)
End Sub
Try to use as follows:
Directory.GetFiles("C:\Users\" & username & "\Documents\MySolution\MyProjects").Where(Function(f)
Return New IO.FileInfo(f).Attributes & IO.FileAttributes.Hidden & IO.FileAttributes.System = 0

vb.net ~ How to add folder names from a directory to a list box

I'm trying to add folder names from within a directpory specified by the user to a list box. I have tried a few solutions, but can't seem to add any items. Most recently I tried:
For Each folder As String In System.IO.Path.GetDirectoryName("D:\")
ListBox1.Items.Add(folder)
Next
The form was built using VB in VB Studio Express 2013. There were no errors when running the program.
If anyone can point me in the right direction, then please help!
If you want to have a list of Directories you need to call Directory.GetDirectories(path), not Path.GetDirectoryName(path) that, in your case returns just null (passing the root directory of a drive)
For Each folder As String In System.IO.Directory.GetDirectories("D:\")
ListBox1.Items.Add(folder)
Next
if you want to show only the folder name and not the full path, just use
For Each folder As String In System.IO.Directory.GetDirectories("D:\")
ListBox1.Items.Add(Path.GetFileName(folder))
Next
Yes, I know, it seems wrong to ask for GetFileName over a folder name, but passing a full path to GetFileName returns just the folder without the path.
how to select folder name to preview picture
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each folder As String In System.IO.Directory.GetDirectories("C:\Program Files (x86)\KONAMI\Pro Evolution Soccer 2016\SFXPath\SweetFX")
ListBox1.Items.Add(Path.GetFileName(folder))
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
If ListBox1.SelectedItem = "folder" Then PictureBox1.ImageLocation = "C:\Program Files (x86)\KONAMI\Pro Evolution Soccer 2016\SFXPath\SweetFX\HD Natural by pimplo\preview.jpg"
End Sub
End Class

Save file path on show dialog

I want to save path on text box after Directory 1: whenever I try to close the application and open again the path is not there.I want it to show every time I open the application.
Private Sub btnRootBrowse1_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse1.Click
RootFolderBrowserDialog.ShowDialog()
txtPath1.Text = RootFolderBrowserDialog.SelectedPath
End Sub
You need save your data (in this case txtPath1.Text) to Hard-Drive (File or DataBase) and reload it in the next execution.
It can be easy when you use Application-Setting:
In the Solution Explorer, Double-Click "My Project"
in left pane click "Setting"
in the table, Fill in the fields as needed, example for you case: Name: DirectoryLocation Type: String Scope: User Value: Empty.
Sample Code Using:
Public Sub New()
InitializeComponent()
'load from the hard-disk
txtPath1.Text = My.Settings.DirectoryLocation
End Sub
Private Sub btnRootBrowse1_Click(sender As System.Object, e As System.EventArgs) Handles btnBrowse1.Click
RootFolderBrowserDialog.ShowDialog()
txtPath1.Text = RootFolderBrowserDialog.SelectedPath
'save to hard-disk
My.Settings.DirectoryLocation = txtPath1.Text
My.Settings.Save()
End Sub

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?

VB.NET - How to Drag a File From Outlook 2010 to My Form?

I'm developing an application to read XML files, get its data and populate some field. SO, I've implemented two ways to get the file: through a command button and through the drag and drop form event. Everything is OK if I use a file stored in a folder in my computer. I can drag the file, the cursor changes its appearance to the copy effect etc. However, when I try doing it dragging a file as an attachment of Outlook (my version is the 2010), I see that the cursor assumes the forbidden effect and the file is not read.
Please, see below the implementation I did, which is working only for files stored in a folder in my computer. I would like to know what more I have to implement to allow drag a file from Outlook.
Thank you in advance.
Private Sub FrmJIG_DragDrop(sender As Object, e As DragEventArgs) _
Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
Dim filestype() As String
filestype = e.Data.GetData(DataFormats.FileDrop)
Dim sReader As New StreamReader(filestype(0))
'get the filename from the file without the path
Dim file_name As String = Path.GetFileName(filestype(0))
'check the extension of the file
If Path.GetExtension(filestype(0)).ToLower() = ".xml" Then
'Read the xml file
For Each path In files
ReadXMLFile(path)
Next
Else
'warning about the file type
MessageBox.Show("Only XML files are supported!", "Warning!", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
End If
End Sub
Private Sub FrmJIG_DragEnter(sender As Object, e As DragEventArgs) _
Handles Me.DragEnter
'change the cursor type to drag and drop type
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Please try with
Private Sub FrmJIG_DragEnter(sender As Object, e As DragEventArgs) _
Handles Me.DragEnter
'change the cursor type to drag and drop type
If e.Data.GetDataPresent(DataFormats.FileDrop) or e.Data.GetDataPresent("FileGroupDescriptor") Then
e.Effect = DragDropEffects.Copy
End If
End Sub