GetDirectory will not list all Directories - vb.net

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

Related

Copy a File Using DragDrop VB.Net

What is wrong with my code? Getting a 'Process cannot access the file because it is being used by another process' error msg Is there a way around this. My google-fu was not giving me much luck. I was not able to Move or Copy, and I will take either.
Private Sub frmFiberTransMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub frmFiberTransMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim filePaths As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
Call CopyFileDrop(filePaths)
End If
End Sub
Private Sub CopyFileDrop(filePaths As String())
For Each fileLoc As String In filePaths
Dim fileName As String = fileLoc
Dim fi As New IO.FileInfo(fileName)
File.Create(fileName)
Dim justFileName As String = fi.Name
Dim newPathName As String = gProgDir & "\" & justFileName
Directory.Move(fileLoc, newPathName)
Next fileLoc
End Sub
File.Create(fileName) returns an open handle and you're not closing it. It doesn't look like you need that line. –
#LarsTech 50 mins ago

Go upper folder/directory VB.NET

I'm making a file/folder explorer using a ListView, when clicking a folder, it shows its contents, but I can't make it go back to where I was before opening that folder, or better going on an upper folder. example I'm in D:\Folder1\Subfolder1\Subfolder and I want to go to its upper folder, I should be in D:\Folder1\Subfolder1, Everytime I click a button.
And i have this code but what it does is it replaces all paths, making it looks like this D:\Folder1 and I can't go back further. By the way the Textbox has a default value/text of D:\Folder.
this is my code:
Dim lvs As String
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
lvs = ListView1.SelectedItems(0).Text.ToString
Form2.TextBox1.Text = Form2.TextBox1.Text & "\" & lvs
End Sub
Private Sub Button5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim s As String = Form2.TextBox1.Text
s.Replace("\" & lvs, " ").TrimEnd()
End Sub
UPDATE
Hi, I updated my code, what I did was I'm putting the ListView items in an Array and I'm deleting the last element(the last folder path) and it works fine. but when I run my code, It only execute once and it cannot be repeated, what could be wrong?
code:
Dim lvs As New List(Of String)
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
If ListView1.SelectedItems.Count > 0 Then
For Each item As ListViewItem In ListView1.SelectedItems
lvs.Add(item.Text)
Next
End If
Form2.TextBox1.Text = Form2.TextBox1.Text & "\" & ListView1.SelectedItems(0).Text
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Label5.Text = Label5.Text.Replace("\" & lvs.ElementAt(lvs.Count - 1), "")
End Sub
You'd need to store the full path to the current folder in a string variable. You would then get the path of the parent folder by:
Dim parentPath As String = IO.Path.GetDirectoryName(currentPath)
Once you've done that you then need to make that new path the current path, which is probably what you weren't doing before. You probably just kept using the same base path to get the parent.
Here is an good sample : https://code.msdn.microsoft.com/windowsapps/Get-upper-folders-in-443e975a
Hopes this help you.
Simple way do this:
Dim path As String = #"C:\Folder1\Folder2\Folder3\Folder4"
Dim newPath As String = Path.GetFullPath(Path.Combine(path, #"..\"));
If you want to go 2level up then try #"..\..\"
Dim Child As String = "C:\Parent\Child"
Dim Parent As String = System.IO.Directory.GetParent(Child).FullName
Someone helped me with my updated code that i just have to put this lvs.RemoveAt(lvs.Count - 1), because i was only removing the item in the Label but not in the List(Of String)(that i thought is an Array, haha).
My Button should look like this:
Label5.Text = Label5.Text.Replace("\" & lvs(lvs.Count - 1), "")
lvs.RemoveAt(lvs.Count - 1)

how to copy file to new directory using openfiledialog in 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

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