Search code examples
vb.netdirectoryfile-extensionmovefile

How can I move a certain file extension into one folder with VB


I am new to VB and would like to create a software that moves a certain file extension into a single folder. I have already built the code that creates a folder on the desktop when clicking the button although after that runs I need to compile a certain file such as (.png) into the folder in created.

This code creates two buttons that when pressed creates a folder called "Pictures" and "Shortcuts". How would I go about moving all .png files from the desktop into the pictures folder?

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        My.Computer.FileSystem.CreateDirectory(
  "C:\Users\bj\Desktop\Pictures")
        MessageBox.Show("Pictures Compiled And Cleaned")
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Shortcuts")
        MessageBox.Show("Shortcuts Compiled And Cleaned")
    End Sub
End Class

Solution

  • We'll start simple. This command will generate an array of all the PNG files' paths on the desktop

    Dim filePaths = Io.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
    

    We can loop through this array and act on each filepath:

    For Each filePath in filePaths
        Dim filename = Io.Path.GetFilename(filepath)
        Dim newPath = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename)
    
        IO.File.Move(filePath, newPath)
    
    Next filePath
    

    We have to pull the filename off the path and put it into a new path, then move from old to new. This I also how you rename files; have a new name in the same folder and use Move. Always use the Path class to cut and combine file paths