You are here: Home > Articles > Article Display

Copying a directory in ASP.NET

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.

Published: Nov 25, 2002 | Last Edited: Aug 20, 2005
Tested with: ASP.NET 1.1
Category: ASP.NET
37,197 views

Introduction

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.

1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <html>
3 <head>
4 <style TYPE="text/css">
5 body {
6     font-family: Verdana;
7     font-size: 70%;
8 }
9 table tr td {
10     font-family: Verdana;
11     font-size: 70%;
12 }
13 </style>
14 </head>
15
16 <body>
17     <h4>Copying a Directory with ASP.NET</h4>
18     <form runat="server">
19         <table border="0" cellpadding="3" cellspacing="2" bgcolor="#cccccc">
20             <tr>
21                 <td>Type the source directory:</td>
22                 <td><asp:TextBox Runat="server" ID="tbxSourceDir"></asp:TextBox></td>
23             </tr>
24             <tr>
25                 <td>Type the destination directory:</td>
26                 <td><asp:TextBox Runat="server" ID="tbxDestinationDir"></asp:TextBox></td>
27             </tr>
28             <tr>
29                 <td colspan="2"><asp:Button Runat="server" ID="btnCopy" OnClick="Copy_Click" Text="Click to Copy"></asp:Button></td>
30             </tr>
31         </table>
32         <br>
33         <asp:Label Runat="server" ID="lblStatusMessage" Visible="False" ForeColor="#ff0000"></asp:Label>
34     </form>
35 </body>
36 </html>

The result of the above HTML source code is this:

resulting Web Form to test the method

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


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

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:

Example of some inputs inside our web form

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.

1 ...
2 Private Sub CopyDirectory(sourcePath As String, destPath As String, overwrite As Boolean)
3     Dim sourceDir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(sourcePath)
4     Dim destDir As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(destPath)
5     'the source directory must exist for our code to run
6     If (sourceDir.Exists) Then
7         'if the destination folder does not exist, create it
8         If Not (destDir.Exists) Then
9             destDir.Create()
10         End If
11         'loop through all the files of the current directory
12         'and copy them if overwrite=true or they do not exist
13         Dim file As System.IO.FileInfo
14         For Each file In sourceDir.GetFiles()
15             If (overwrite) Then
16                 file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), True)
17             Else
18                 If ((System.IO.File.Exists(System.IO.Path.Combine(destDir.FullName, file.Name))) = False) Then
19                     file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), False)
20                 End If
21             End If
22         Next
23         'loop through all the subfolders and call this method recursively
24         Dim dir As System.IO.DirectoryInfo
25         For Each dir In sourceDir.GetDirectories()
26             If (dir.FullName <> Server.MapPath(tbxDestinationDir.Text)) Then
27                 CopyDirectory(dir.FullName, System.IO.Path.Combine(destDir.FullName, dir.Name), overwrite)
28             End If
29         Next
30         lblStatusMessage.Text = "Folder copied successfully"
31         lblStatusMessage.Visible = True
32     'if source directory does not exist
33     Else
34         lblStatusMessage.Text = "Error: source folder does not exist!"
35         lblStatusMessage.Visible = True
36     End If
37 End Sub
38 </script>
39 ...

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:

Successful attempt to copy a directory

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

Unsuccessful attempt to copy a directory

Conclusion

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.

 



Other articles in this category
  1. Smart headers and footers using ASP.NET User Controls
    December 23, 2002
    Good site usability often means removing links from one page back to itself. In this article we will look at how to create an ASP.NET User Control which will act as a common header to a site. It will automatically know which page we are looking at, and it will remove links to the same page from itself. For example, on this site, if we click on the About us section of the header, it will take you to the page, and it will make that link inactive. That way, we know that we are under that section, and we can't click on it anymore.
  2. Maintaining Sorting while Paging in an ASP.NET Datagrid
    December 18, 2002
    The Datagrid server control offers much control and flexibility in presenting data. Two of the actions that are hard-wired into it are Paging and Sorting. On their own they work great, but not so well together. When you sort a column and then move to a previous or next page, the sorting preference is not maintained. In this article we will see how to maintain both by using the Viewstate object.
  3. How postback works in ASP.NET
    December 10, 2002
    In this article, we will take a closer look at how ASP.NET pages post back to themselves, and how to customize this feature in our web applications.
  4. Viewing and editing file and directory attributes in ASP.NET
    December 2, 2002
    The System.IO.FileAttributes class gives us access to file/directory attributes. In this article, we'll see how to use this class to first read the current attributes and then change them.
  5. Creating and consuming a Web Service using Visual Studio .NET
    November 18, 2002
    This article will go through the complete process of how to create a Web Service and then how to consume it in any ASPX page. We'll do this entirely within the Visual Studio.NET. Our Web Service will convert Fahrenheit degrees to Celcius.