JackSparrow
JackSparrow

Reputation: 389

How to move multiple files using vb.net

Is it possible to move all files/folders in one directory that contain some words and move them to another? So for example all files/folders called 'Testing this' and moving them to another folder? I try the following but its not working? The words 'testing this' could be shown anywhere in the file name.

   Dim directory = "C:\Test\"
        For Each filename As String In IO.Directory.GetFiles(directory, "testing this", IO.SearchOption.AllDirectories)
            My.Computer.FileSystem.MoveFile(filename, "C:\Test\Old\" & "testing this")
        Next

Upvotes: 0

Views: 9843

Answers (2)

Steve
Steve

Reputation: 216293

No, the My.Computer.FIlesSystem.MoveFile can move only one file for each call.
You need to build a loop around your source directory and move each file one by one

Dim sourceDir = "C:\test"
For Each file As String In My.Computer.FileSystem.GetFiles( sourceDir, _

    Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*testing this*")

    Dim destPath = file.Substring(sourceDir.Length + 1)
    Dim destFile = System.IO.Path.GetFileName(file)

    My.Computer.FileSystem.MoveFile(file, _
               System.IO.Path.Combine("C:\Test\Old", destPath, destFile ))
Next

Upvotes: 1

Brandon
Brandon

Reputation: 4593

You can use wildcards in the GetFiles method.

So:

Dim directory = "C:\Test\"
        For Each filename As String In IO.Directory.GetFiles(directory, "*testing this*", IO.SearchOption.AllDirectories)
            My.Computer.FileSystem.MoveFile(filename, "C:\Test\Old\" & "testing this")
        Next

Upvotes: 1

Related Questions