Copy, delete and move files in VB.NET

The System.IO namespace contains classes and methods for copying, deleting, and moving files and folders in VB.NET. This includes working with files on network or shared drives.

This method shows how to delete files in a folder. Using System.IO class Directory class we will check whether the folder name in "sourcePath" exists or not. If directory is not present in the disk then we will create it. Then we will check any files are present in that folder. If present then we loop through all files one by one and delete those file using File.Delete method.

Public Sub DeleteFilesFromFolders(ByVal sourcePath As String)
If (Directory.Exists(DirPath)) Then
For Each fName As String In Directory.GetFiles(DirPath)
If File.Exists(fName) Then
File.Delete(fName)
End If
Next
End If
End Sub

' This method shows how to move files from one folder to another folder.

Public Sub MoveFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
If (Directory.Exists(sourcePath)) Then
For Each fName As String In Directory.GetFiles(sourcePath)
If File.Exists(fName) Then
Dim dFile As String = String.Empty
dFile = Path.GetFileName(fName)
Dim dFilePath As String = String.Empty
dFilePath = DestinationPath + dFile
File.Move(fName, dFilePath)
End If
Next
End If
End Sub

' This method shows how to copy files from one folder to another folder.

Public Sub CopyFiles(ByVal sourcePath As String, ByVal DestinationPath As String)
If (Directory.Exists(sourcePath)) Then
For Each fName As String In Directory.GetFiles(sourcePath)
If File.Exists(fName) Then
Dim dFile As String = String.Empty
dFile = Path.GetFileName(fName)
Dim dFilePath As String = String.Empty
dFilePath = DestinationPath + dFile
File.Copy(fName, dFilePath, True)
End If
Next
End If
End Sub

By Cos mos   Popularity  (43263 Views)