Opening listview items with a double click vb.net - vb.net

I want to open items from a list view with a double click.
Imports System.IO
Imports System.Xml
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
lstvicon.Columns.Add("Nome")
lstvicon.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim items() As ListViewItem = lstvicon.SelectedItems.Cast(Of ListViewItem).ToArray
Dim csv() As String = Array.ConvertAll(items, Function(lvi) String.Join(",", lvi.SubItems.Cast(Of ListViewItem.ListViewSubItem).Select(Function(si) si.Text).ToArray))
IO.File.WriteAllLines("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", csv)
End Class
That's the important part of the code, I was think of using onclick but I cant seem to get anywhere with it, any suggestions?
I also considered using and Open File Dialog but I dont think it can be done without the user's input of a path

I'm assuming that when you say open, you mean you want to open the associated file in the default program for that file type. In that case, you need to be storing the full path to the file in the list view. That can be accomplished via this code:
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.Tag = file.FullName
Next
You will then need to add an event for the listview's double-click method. Within that event you'll want to look at the selected item and run the default program for it.
Private Sub lstvicon_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstvicon.DoubleClick
Process.Start(lstvicon.SelectedItems(0).Tag)
End Sub

Related

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)

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

Listview items and saving them as .csv

I'm doing this project where I need to save the names of the items from a listview to a .csv
Imports System.IO
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim returnValue As String()
returnValue = Environment.GetCommandLineArgs()
If returnValue.Length > 1 Then
MessageBox.Show(returnValue(1).ToString())
Else
MessageBox.Show("Nothing")
End If
' Set ListView Properties
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
' Create Columns Headers
lstvicon.Columns.Add("Nome")
lstvicon.Columns.Add("Extensão")
lstvicon.Columns.Add("Tamanho")
lstvicon.Columns.Add("Data Modificação")
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.SubItems.Add(file.Extension)
li.SubItems.Add(file.Length)
li.SubItems.Add(file.LastWriteTimeUtc)
'li.SubItems.Add(FileDialog)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
' Creates a csv File
Dim csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
lstvicon.SelectedItems.CopyTo(csv)
csv.Close()
End Sub
End Class
That's what I got but I can't seem to get it to write on the .txt.
I have no idea where to go from here and i've been going around this for hours, so any help would be apreciated.
I think that you want something like this:
' Creates a csv File
Using csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
For Each oItem As ListViewItem In ListView1.Items
csv.WriteLine(String.Format("""{0}"",""{1}"",{2},{3}", oItem.Text, oItem.SubItems(0).Text, oItem.SubItems(1).Text, oItem.SubItems(2).Text )
Next
End Using
You will probably need to clean up the csv formatting, but this should give you an idea.