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

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!",
				sourceDirectory));
	}

	if (!Directory.Exists(destinationDirectory))
	{
		Directory.CreateDirectory(destinationDirectory);
	}

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

	if (!recursive)
	{
		return;
	}
	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
            Directory.CreateDirectory(destinationDirectory)
        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)
        Next
        If Not recursive Then
            Return
        End If
        For Each subdir As var In dirs
            Dim temppath As var = Path.Combine(destinationDirectory, subdir.Name)
            RecursiveFolderCopy(subdir.FullName, temppath, recursive)
        Next
    End Sub

Please Share us:
Please rate this snippet

3 thoughts on “How to copy a Folder/Directory recursive in C# and VB.NET

Leave a Reply