How to copy a Folder/Directory recursive in C# and VB.NET.

Sample C#

public void RecursiveFolderCopy(string sourceDirectory, string destinationDirectory, bool recursive)
	var dir = new DirectoryInfo(sourceDirectory);
	var dirs = dir.GetDirectories();

	if (!dir.Exists)
		throw new DirectoryNotFoundException(
			String.Format("Source directory {0} does not exist!",

	if (!Directory.Exists(destinationDirectory))

	var files = dir.GetFiles();
	foreach (var file in files)
		var temppath = Path.Combine(destinationDirectory, file.Name);
		file.CopyTo(temppath, false);

	if (!recursive)
	foreach (var subdir in dirs)
		var temppath = Path.Combine(destinationDirectory, subdir.Name);
		RecursiveFolderCopy(subdir.FullName, temppath, recursive);

Sample VB.NET

Public Sub RecursiveFolderCopy(ByVal sourceDirectory As String, ByVal destinationDirectory As String, ByVal recursive As Boolean)
        Dim dir As var = New DirectoryInfo(sourceDirectory)
        Dim dirs As var = dir.GetDirectories
        If Not dir.Exists Then
            Throw New DirectoryNotFoundException(String.Format("Source directory {0} does not exist!", sourceDirectory))
        End If
        If Not Directory.Exists(destinationDirectory) Then
        End If
        Dim files As var = dir.GetFiles
        For Each file As var In files
            Dim temppath As var = Path.Combine(destinationDirectory, file.Name)
            file.CopyTo(temppath, false)
        If Not recursive Then
        End If
        For Each subdir As var In dirs
            Dim temppath As var = Path.Combine(destinationDirectory, subdir.Name)
            RecursiveFolderCopy(subdir.FullName, temppath, recursive)
    End Sub

One thought on “How to copy a Folder/Directory recursive in C# and VB.NET”

Leave a Reply