how to copy file to new directory using openfiledialog in vb.net? - vb.net

I need to copy an mp3 file chosen with OpenFileDialog to a new directory. The problem is all the files inside the folder copies to the new directory. I want to copy only the specific file chosen in that folder. pls help.
note: after opening the mp3 file, Textbox1 will display the source path of the file(sourcepath). then Textbox2 will display the new path(destPath) after hitting the save button.
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
For Each file__1 As String In Directory.GetFiles(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
File.Copy(file__1, dest)
Next
For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(sourcePath))
Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
CopyDirectory(folder, dest)
Next
End Sub
Private Sub ButtonSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSave.Click
Dim sourcepath As String = ""
Dim DestPath As String = "C:\Users\Big Boss Eis\Desktop\vb file maintenance\fileMaintenance with database\fileMaintenance"
sourcepath = TextBox1.Text
CopyDirectory(sourcepath, DestPath)
End Sub
Private Sub OpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenFile.Click
If (OpenFileDialog1.ShowDialog = DialogResult.OK) Then
AxWindowsMediaPlayer1.URL() = OpenFileDialog1.FileName
TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub

Replace your entire CopyDirectory function with this
Private Shared Sub CopyDirectory(ByVal sourcePath As String, ByVal destPath As String)
If System.IO.File.Exists( sourcePath ) = True Then
System.IO.File.Copy( sourcePath , destPath )
MsgBox("File Copied")
End If
End Sub
Edited through mobile phone, excuse any errors

Related

VB.NET 2008 Not recognizing Path.GetFileName Method

I have read this post but nothing works.
Visual Basic not recognizing Path.GetFileName Method
I am following this page in trying to get the filename in my Visual Basic application but i can't compile it Microsoft Official Page
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
size_mode_list.Items.AddRange([Enum].GetNames(GetType(PictureBoxSizeMode)))
For Each drive As DriveInfo In DriveInfo.GetDrives
Dim node As TreeNode = _
file_view_tree.Nodes.Add(drive.Name)
node.Tag = ItemType.Drive
node.Nodes.Add("FILLER")
Next
End Sub
Private Sub file_view_tree_BeforeExpand(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles file_view_tree.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 dolderString 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.Folder
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
'Don't forget to import this
Imports System.IO
'Declare these
Private Enum ItemType
Drive
Folder
File
End Enum
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each drive As DriveInfo In DriveInfo.GetDrives
Dim node As TreeNode = _
file_view_tree.Nodes.Add(drive.Name)
node.Tag = ItemType.Drive
node.Nodes.Add("FILLER")
Next
End Sub
Private Sub file_view_tree_BeforeExpand(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles file_view_tree.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.Folder
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

How to display a random photo from a folder in a picture box and print out the photo name without extension

I have a folder named "MyPhotos", I want to display a random photo at each time a command button is clicked from "Myphoto" and print out the name of the displayed photo in the form without extension . I'm trying the following code, but still can't get the photo name
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim DirectoryPath As String = Application.ExecutablePath
Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
Dim bm As New Bitmap(GetRandomImageFilePath(Directorypath))
picImage.Image = bm
End Sub
Public Function GetRandomImageFilePath(ByVal folderPath As String) As String
Dim files() As String = Directory.GetFiles(folderPath, "*.jpg")
Dim random As Random = New Random()
Return files(random.Next(0, files.Length))
End Function
Any help please ?
I added this to your button method. All I used was FileInfo to get the details.
Dim finfo As FileInfo = New FileInfo(GetRandomImageFilePath(DirectoryPath))
Dim filename As String = finfo.Name.Replace(finfo.Extension, "")
Dim bm As New Bitmap(finfo.FullName)
picImage.Image = bm
You already have the full path being returned by GetRandomImageFilePath.
If you want just the filename, do this in your calling Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim DirectoryPath As String = Application.ExecutablePath
Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
Dim imagePath as String = GetRandomImageFilePath(Directorypath)
Dim fileInfo as New FileInfo(imagePath)
Dim imageName as String = fileInfo.Name
Dim bm As New Bitmap(imagePath)
picImage.Image = bm
End Sub

GetDirectory will not list all Directories

I have a form that allows you to click a button, which triggers an OpenFileDialog. From there, you are suppose to select a specific file within that folder, and then the program is supposed to go through from the folder you were in the the /subjects folder and list those directories.
At the moment, I have 3 directories within /subjects: english, mathematics, and cte.
My issue is that when the program is ran, it will only list the English directory in the combo-box, and will not list any of the others.
Private Sub btnDocumentChoice_Click(sender As Object, e As EventArgs) Handles btnDocumentChoice.Click
Dim ofd As New OpenFileDialog
Dim DirList As New ArrayList
If ofd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso ofd.FileName <> "" Then
strRootLocation = (Path.GetDirectoryName(ofd.FileName))
GetDirectories(strRootLocation + "/subject/", DirList)
'MessageBox.Show(Path.GetDirectoryName(ofd.FileName))
End If
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
strRootLocation = OpenFileDialog1.FileName
cmbSubject.Items.Add(strRootLocation)
End Sub
Sub GetDirectories(ByVal StartPath As String, ByRef DirectoryList As ArrayList)
Dim Dirs() As String = Directory.GetDirectories(StartPath)
DirectoryList.AddRange(Dirs)
For Each Dir As String In Dirs
GetDirectories(Dir, DirectoryList)
cmbSubject.Items.Add(Replace(Path.GetDirectoryName(Dir), strRootLocation + "\subject", ""))
cmbSubject.Items.Remove("")
Next
End Sub
I managed to fix my own issue by removing the For Each loop in the question, and replacing it with this:
Dim directories As String
For Each directories In Directory.GetDirectories(strRootLocation + "\subject")
cmbSubject.Items.Add(Replace(directories, strRootLocation + "\subject\", ""))
Next

Deleting Specific Files and then Extract them into another folder

With the following code I am trying to delete specific files inside of a folder on a flash drive, and then copy the remaining files into a separate folder. When the program runs and I initiate the button to do so, the program deletes files that have not been modified within the past year, but then it does not continue to extract the remaining files and place them into a separate folder.
Does anyone know why?
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
DeleteUnmodifiedFiles(sourceDirectory, 365)
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)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
Private Sub DeleteUnmodifiedFiles(ByVal directoryName As String, ByVal modificationThresholdDays As Integer)
Dim folder As New DirectoryInfo(directoryName)
Dim thresholdDate As Date
Dim wasModifiedSinceThreshold As Boolean
For Each file As FileInfo In folder.GetFiles
thresholdDate = DateTime.Now().AddDays(-1 * modificationThresholdDays)
wasModifiedSinceThreshold = (file.LastWriteTime > thresholdDate)
If (Not wasModifiedSinceThreshold) Then file.Delete()
Next
MessageBox.Show("Deleting Files")
End Sub
End Class
This will delete any file in the source directory that hasn't been modified for a year, and then will move any remaining files to the destination directory...
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim fileListA() As String
fileListA = (IO.Directory.GetFiles("C:\Scource_Directory"))
For Each i As String In fileListA
If (IO.File.GetLastWriteTime(i).ToShortDateString.Substring(6)) < (CType(DateTime.Now.Year.ToString, Integer) - 1) Then
IO.File.Delete(i)
End If
Next
Dim fileListB() As String
fileListB = (IO.Directory.GetFiles("C:\Scource_Directory"))
For Each i As String In fileListB
IO.File.Move(i, "Destination_Directory")
Next
End Sub

Open Excel Workbook from ComboBox (VB.NET)

How to open an excel workbook from combobox?
I am using following code to populate combobox with excel filenames,
Dim files() As String
files = Directory.GetFiles("C:\Files\Folder", "*.xlsx", SearchOption.AllDirectories)
For Each FileName As String In files
ComboBox1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
But I do not have any idea about how to open the selected file.
Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Private Const TargetDir = "C:\Files\Folder"
Private FullFileList As List(Of String)
Private Sub ProcessFile(ByVal fn As String)
If Path.GetExtension(fn).ToLower = ".xlsx" Then
FullFileList.Add(fn)
ComboBox1.Items.Add(Path.GetFileName(fn))
End If
End Sub
Private Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
Dim fileName As String
For Each fileName In fileEntries
ProcessFile(fileName)
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FullFileList = New List(Of String)
ProcessDirectory(TargetDir)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then
Dim prc As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo(FullFileList(ComboBox1.SelectedIndex))
psi.UseShellExecute = True
psi.WindowStyle = ProcessWindowStyle.Normal
prc.StartInfo = psi
prc.Start()
End If
End Sub
End Class
You'll need to handle an event to react to the user's selection: either a change to the selection in the ComboBox or (better) a Button click. In your event handler you can retrieve the filename from the ComboBox:
string filename = ComboBox1.SelectedItem.ToString()
Once you have the filename, you can open the file, although how you do this will depend on what you want to do with it. This answer has some information on opening Excel files in VB.NET.
Try using
Process.start("excel "+ComboBox1.SelectedItem.ToString());
on buttonclick event