How to Move a File with VB .NET

This lesson is part of an ongoing tutorial. The first part is here: How to open a Text File in VB .NET

 

You move a file in a similar manner as you did to Copying a File - specify a source file and a new destination for it. This time, we use the Move method of System.IO.File. Here's some code:

Dim FileToMove As String
Dim MoveLocation As String

FileToMove = "C:\Users\Owner\Documents\test.txt"
MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"

If System.IO.File.Exists( FileToMove ) = True Then

System.IO.File.Move( FileToMove, MoveLocation )
MessageBox.Show("File Moved")

End If

The above code assumes that you have created a folder on your hard drive called "TestFolder":

MoveLocation = "C:\Users\Owner\Documents\TestFolder\test.txt"

The file called test.txt will then be moved inside of this new location. You can give it a new name, if you want. In which case, just change the name of the file when you're moving it:

MoveLocation ="C:\Users\Owner\Documents\TestFolder\NewName.txt"

Again though, the thing to type in the round brackets of the method is first the Source file, then the Destination.

System.IO.File.Move( FileToMove, MoveLocation )

In the final part of this section, you'll learn how to Delete a File using VB .NET code.

Buy our VB NET Book Here