1

我有一个文件夹 (1) 将填满文件,这些文件将显示在 ListViewBox 中,旁边有一个复选框。我试图弄清楚当按下 Button1 并选中文件名旁边的复选框时,它将将该文件移动到下一个文件夹(2)。(想法是文件夹 1 中可能有 10 个文件,用户可以选择将哪些文件移动到文件夹 2)。

我正在努力让For Each循环为我工作ListView。我曾尝试使用My.Computer.Filesystem.Moveand IO.File.Move,但我很难将它们与每个文件一起更改的文件名与列表视图框中的选中项目联系起来。任何帮助将不胜感激。

这是我的代码:

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
4

2 回答 2

1

在您的按钮单击事件处理程序中,遍历CheckedItems集合,然后将文件从源目录移动到目标目录并附加正确的文件扩展名。

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
于 2013-09-11T20:52:33.767 回答
1

您必须遍历 ListView1 中的元素并移动所需的元素(并将它们从列表中删除)。

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

注意:我正在添加一个 try...catch,因为“文件管理”往往会出现问题(并且该Move方法非常不灵活)。

于 2013-09-11T20:54:23.250 回答