I have a folder(1) that will fill up with files and those files will show in the ListViewBox with a checkbox next to it. I am trying to figure out that when Button1 is pressed and the checkbox next to the file name is checked, it will move that file to the next folder(2). (The idea is that there could be 10 files in the folder1 and the user could choose which files to move to folder2).
I am struggling to get the For Each
loop working for me using ListView
. I have tried using My.Computer.Filesystem.Move
and IO.File.Move
, but I am having a hard time tying them file name which changes with every file to the checked item in the listview box. Any help would be greatly appreciated.
Here is my code:
Public Class Form1
Public MySource As String = "C:\DataEntryTest\LogFiles\"
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim folderinfo As IO.DirectoryInfo = New IO.DirectoryInfo(MySource)
ListView1.FullRowSelect = True
ListView1.CheckBoxes = True
With ListView1
.Clear()
.View = View.Details
.Columns.Add("Name", 150)
For Each myFile As IO.FileInfo In folderinfo.GetFiles
Dim myListItem As ListViewItem = New ListViewItem(myFile.Name)
.Items.Add(myListItem)
Next
End With
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
End Class
In your button click event handler, loop through the CheckedItems
collection, then move the file from the source directory to the target directory and append the correct file extension.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each itemChecked As Object In ListView1.CheckedItems
Dim itemName As String = itemChecked.ToString()
File.Move(Path.Combine(MySource, itemName), Path.Combine(MyTarget, itemName)
Next
End Sub
You have to iterate through the elements in ListView1 and move the required ones (and removing them from the list).
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim destDir As String = "dir to move-to path"
With ListView1
For i As Integer = .Items.Count - 1 To 0 Step -1
If .Items(i).Checked Then
Try
Dim newPath As String = destDir & Path.GetFileName(.Items(i).Text)
If Not File.Exists(MySource & .Items(i).Text) Then
.Items(i).Remove()
Else
If Not File.Exists(newPath) Then
File.Move(MySource & .Items(i).Text, newPath)
.Items(i).Remove()
End If
End If
Catch
End Try
End If
Next
End With
End Sub
NOTE: I am adding a try...catch, because "file management" tends to be problematic (and the Move
method is quite unflexible).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.