0

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
Brenduan
  • 9
  • 5

1 Answers1

0

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

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • Awesome, thank you. Just what I was looking for! If I was to also compile jpg images into the picture folder is this how I would add that in? ( "*.png" , "*.jpg") – Brenduan Apr 09 '20 at 06:05
  • @Brenduan, when you read the documentation for the `GetFiles` method, did it imply that that would be the case? You can look for yourself. Just click the method name and press the F1 key. Context-sensitive Help in Windows has been a thing for decades. – jmcilhinney Apr 09 '20 at 06:15
  • You'll have to do it as two operations. There is no facility for "this extension or that extension". On the same way as I have used a foreach loop here to loop through a list of file strings you could make an array of all the extensions you want and then foreach loop through it, so you'll have a foreach loop inside a foreach loop, one loop doing the files and the other doing the extensions – Caius Jard Apr 09 '20 at 06:56