仅移动具有特定扩展名的文件

时间:2013-12-07 22:26:07

标签: vb.net visual-studio-2012

我目前正在使用Directory.Move方法将文件从一个位置复制到另一个位置。我想做的只是移动具有特定扩展名的文件(.dbf,.ini& .txt)。如果原始文件夹不包含任何这些文件,那么我只想创建一个空目录

我正在使用的当前代码是......

Dim n As Integer

If lb1.SelectedItems.Count = 0 Then Exit Sub

For n = 0 To UBound(AllDetails)

    If AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps = lb1.SelectedItem Then

        If Not My.Computer.FileSystem.DirectoryExists(aMailbox & "\" & AllDetails(n).uFile) Then
            Directory.Move(zMailbox & AllDetails(n).uFile, aMailbox & "\" & AllDetails(n).uFile)
            lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
        Else

            lb3.Items.Add(AllDetails(n).uName & " - " & AllDetails(n).uCode & " - " & AllDetails(n).uOps)
            Exit Sub
        End If
    End If
Next

声明了所有变量,这可以工作但移动整个文件夹内容

2 个答案:

答案 0 :(得分:2)

解决此问题的一种方法是将每个扩展名用作File.GetFiles的搜索模式,然后在返回的每个文件上使用Directory.Move。这样的事情可能会有所帮助:

    For Each OldFile As String In (From s In {".dbf", ".ini", ".txt"}
                                From f In Directory.GetFiles(zMailbox & AllDetails(n).uFile, s)
                                Select f)
        Directory.Move(OldFile, aMailbox & "\" & AllDetails(n).uFile & "\" & Path.GetFileName(OldFile))
    Next

答案 1 :(得分:0)

如果你想要的只是某些文件扩展名?好Open File Dialog可以为您过滤

假设您通过单击按钮调用此操作:

    Dim fd As OpenFileDialog = New OpenFileDialog()


    fd.Title = "Open File Dialog"
    fd.InitialDirectory = "the initial directory you want to look at first"

    'this filters the available files to be opened!
    fd.Filter = "dbf files|*.dbf*|ini files|*.ini*|Text files|*.txt*"
    fd.FilterIndex = 2 'set's the default files to open first as .ini
    fd.RestoreDirectory = True

    If fd.ShowDialog() = Windows.Forms.DialogResult.OK Then
        'Copy the file to the location using the copyer subroutin
        resulta.Text = fd.FileName.ToString
        Copyer(fd.FileName.Tostring, "the location where you want to copy")
    End If
End Sub

现在要复制文件,看看这个子程序。此子例程首先检查文件是否存在。如果是,则删除它,然后复制新文件。

Public Sub Copyer(ByVal theFile As String, ByVal Lokasyon As String)
    Try

        Dim resultpath As String = Lokasyon
        If System.IO.File.Exists(resultpath) = True Then

            System.IO.File.Delete(resultpath) 
            'this deletes the file so you can overwrite it.
        End If
        My.Computer.FileSystem.CopyFile(theFile, resultpath)
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

如果这有助于你,请告诉我。