The System.IO.DirectoryInfo class does not come with a method to copy a directory. In this article, we’ll see how to create a method to do that, and then use it in an ASP.NET page.

The ASPX web form interface

Before you try this, make sure that you have write access on your web server. Typically, the anonymous user, which is used to access a website, is not allowed such permissions, but will need them to be able to copy folders from one location to another. If you do not want to give write permissions to everybody on your site, then create a new user, grant them the proper permissions, and log in with that account instead.

To begin with, let’s create an ASPX web form where we can test our code.

<!DOCTYPE HTML PUBLIC "<em>-//W3C//DTD HTML 4.0 Transitional//EN"</em><em>></em>
<style TYPE="text/css">
body {
	font-family: Verdana;
	font-size: 70%;
table tr td {
	font-family: Verdana;
	font-size: 70%;

	<h4>Copying a Directory with ASP.NET</h4>
	<form runat="server">
		<table border="0" cellpadding="3" cellspacing="2" bgcolor="#cccccc">
				<td>Type the source directory:</td>
				<td><asp:TextBox Runat="server" ID="tbxSourceDir"></asp:TextBox></td>
				<td>Type the destination directory:</td>
				<td><asp:TextBox Runat="server" ID="tbxDestinationDir"></asp:TextBox></td>
				<td colspan="2"><asp:Button Runat="server" ID="btnCopy" OnClick="Copy_Click" Text="Click to Copy"></asp:Button></td>
		<asp:Label Runat="server" ID="lblStatusMessage" Visible="False" ForeColor="#ff0000"></asp:Label>

The result of the above HTML source code is this:

Our web form contains 2 textboxes, one button and one hidden label web control (to show status messages after clicking on the button). Our button calls a Copy_Click method when clicked, which is responsible for parsing out the source and destination paths, and in turn call a CopyDirectory method, both of which will be shown below.

Adding the Copy_Click method

<%@ Page Language="vb" debug="true" explicit="true" strict="true" %>
<script language="vb" runat="server">
Sub Copy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
	'convert our source path into a physical path
	Dim sourcePath As String = Server.MapPath(tbxSourceDir.Text)
	'get the folder we want to copy from
	Dim arrSourcePath() As String = RegEx.Split(tbxSourceDir.Text, "/")
	Dim lastFolder As String = arrSourcePath(UBound(arrSourcePath))
	'get our destination path as physical
	Dim destPath As String = Server.MapPath(tbxDestinationDir.Text + "/" + lastFolder)
		CopyDirectory(sourcePath, destPath, True)
	Catch exc As System.Exception
		lblStatusMessage.Text = exc.Message
		lblStatusMessage.Visible = True
	End Try
End Sub

As we saw before, the Copy_Click method is called when we click on the button on our web page. It uses the RegEx.Split() method to convert the source directory into an array, based on the “/” characters in the path. We do this so that we can get the last folder name of the source path, and then append that to the destination path.  For example:

Using our parsing, the destination directory will therefore become /test/webmaster/evagoras.  Once we have both our source and correct destination folders, we convert them into physical paths, using the Server.MapPath() method. A physical path is one which gives the complete path of a file/folder in the system, for example C:\inetpub\wwwroot\images\xefteri.gif.  We pass the source and destination paths to the CopyDirectory method, which is nested inside a Try…Catch statement to catch any possible exceptions. Any exceptions are shown through our label web control, lblStatusMessage, on the page.

The CopyDirectory method

A typical method of this kind would include 3 parameters:

  1. Source directory to copy from. Let’s make this a String and call it sourcePath.
  2. Destination directory to copy to. Let’s make this a String again and call it destPath.
  3. Whether to overwrite any files with the same name at the destination directory or not. Let’s make this a Boolean variable and call it overwrite.

Let’s first take a look at the complete code of the method, and then we’ll go through it in more detail.

Private Sub CopyDirectory(sourcePath As String, destPath As String, overwrite As Boolean)
	Dim sourceDir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(sourcePath)
	Dim destDir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(destPath)
	'the source directory must exist for our code to run
	If (sourceDir.Exists) Then
		'if the destination folder does not exist, create it
		If Not (destDir.Exists) Then
		End If
		'loop through all the files of the current directory
		'and copy them if overwrite=true or they do not exist
		Dim file As System.IO.FileInfo
		For Each file In sourceDir.GetFiles()
			If (overwrite) Then
				file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), True)
				If ((System.IO.File.Exists(System.IO.Path.Combine(destDir.FullName, file.Name))) = False) Then
					file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), False)
				End If
			End If
		'loop through all the subfolders and call this method recursively
		Dim dir As System.IO.DirectoryInfo
		For Each dir In sourceDir.GetDirectories()
			If (dir.FullName <> Server.MapPath(tbxDestinationDir.Text)) Then
				CopyDirectory(dir.FullName, System.IO.Path.Combine(destDir.FullName, dir.Name), overwrite)
			End If
		lblStatusMessage.Text = "Folder copied successfully"
		lblStatusMessage.Visible = True
	'if source directory does not exist
		lblStatusMessage.Text = "Error: source folder does not exist!"
		lblStatusMessage.Visible = True
	End If
End Sub

If the source directory is not a valid one, then it doesn’t make sense to do anything. Therefore, we wrap all our code inside an IF statement – only proceed if the source folder exists. Then we check if the destination folder exists or not, and if it doesn’t we create it by using the Create() method. We use the GetFiles() method of the System.IO.DirectoryInfo class to loop through all the files inside the source directory. For each file that we find, we copy it to the destination folder if it’s not there, or if we chose to overwrite everything (despite if it’s there or not). The path to copy the files to, is easily derived by using the System.IO.Path.Combine() method, which joins the folder path with the file name for us.

Then we use the GetDirectories() method of the class to loop through all the subfolders of our source folder, and for each one we find, we call our method recursively. A successful copy would result in a screen like so:

While an unsuccessful attempt, due to a source directory not existing, would result in a screen like so:

We have seen how to copy a directory with ASP.NET, something that is not provided in the extensive library of methods of the .NET framework.  You could use this method for example, in an online file manager to select one folder and copy it to another location.