Files and Folders

Basic File Operations

The basic file operations in in VB are :

Name

Function

FileCopy

Copies a file

Kill

Deletes a file

Name

Renames/moves a file

To copy a file, you use the FileCopy function, which is very simple:

FileCopy SourceFile, DestinationFile

So,

FileCopy "C:\test.txt", "C:\testdir\test2.txt"

copies text.txt to C:\testdir and renames it test2.txt

To delete a file, you use the Kill (!) function.

Kill FilePath

So,

Kill "C:\test folder\test.txt"

deletes text.txt from C:\test folder . This does not send it to the recycle bin! If you want to do this, click here.

To rename/move file:

Name OldNameandPath As NewNameandPath

So,

Name "C:\test.txt" As "C:\test2.txt"

Renames test.txt as test2.txt, and

Name "C:\test.txt" As "C:\testdir\test2.txt"

moves text.txt to C:\testdir and renames is test2.txt You can also use this function to rename folders.

To see if a file exists, you can use the Dir function. If it returns nothing, then the file does not exist:

If Dir(FileName) = "" Then
    '// file does not exist
End If

However, this is not always reliable, especially on a network, and you should really use the WinApi method.

If you want to know how to do these operations using Win API, which allows you to send files to the recycle bin, and display the standard file copying dialog, click here.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra