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 rate this snippet

How to check if a folder contains files in C# and VB.NET

To check if a folder contains files in C# and VB.NET you can use the following snippet below.

Sample C#

public static Boolean HasFilesInFolder(DirectoryInfo directory, string paramFilter)
{
	try
	{
		return directory.GetFiles(paramFilter).Any();
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return false;
	}
}

Sample VB.NET

Public Shared Function HasFilesInFolder(directory As DirectoryInfo, paramFilter As String) As [Boolean]
	Try
		Return directory.GetFiles(paramFilter).Any()
	Catch ex As Exception
		'handle the exception your way
		Return False
	End Try
End Function

Please rate this snippet