Copy, delete and move files in VB.NET
By Cosmos Mysore
In this article we will learn how to delete, copy and move files in VB.NET
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
Popularity (35573 Views)
Article Discussion: Copy, delete and move files in VB.NET
David Taylor replied
to Cosmos Mysore at Sunday, October 31, 2010 2:12 AM
small error in the MoveFiles for vb.net
dfilepath = destinationpath + dfile
doesn't work there is a missing backslash so the above should read lie this
dfilepath = destinationpath + "\" + dfile
Then it works great. Thanks for the help! The article was very informative.