System.IO.Directory.Copy()?


Answer me this, .NET gurus:  <primalscream>Why</primal_scream> does the System.IO.Directory class not include a .Copy() method.  I can Move(), CreateDirectory(), and even Delete(), but I can’t copy a directory and all of its contents recursively?  And don’t even try to tell me that Directory.Copy() doesn’t exist because the .NET team figured that even wannabe programmers like me can create our own .copy() as easily as we can type D-i-r-e-c-t-o-r-y-.-C-o-p-y-(-). 


My attempts to workaround this limitation went like this:



  1. In Visual Studio .NET, I typed System.IO.Directory and press the F1 key. Result: learned a lot about the Directory class that didn’t help me accomplish the task before me.

  2. Searched for Index for keyword “directory.copy“ in Visual Studio .NET.  Result: failure

  3. Searched VS.NET help for “Directory.Copy“. Result: failure.

  4. Created my own dir.Copy() … Result: short attention span…disbelief…decided to consult my friend Google.

  5. Searched Google for “Directory.Copy() +.NET“.  Result: multiple successful hits. Copied sample code snippets* from Web to my project and was successfully copying directories recursively several minutes later.

Takeaways



  • Directory.Copy() should exist, and I am by no means the only .NET developer in the world who thinks this[1].

  • “Directory.Copy” and any other similarly inexplicable class exclusions should in future be added to the MSDN Combined Collection’s index, as should a topic that explains why it is not available in the .NET Framework.

[1]http://www.codeproject.com/csharp/copydirectoriesrecursive.asp
http://www.aspemporium.com/aspEmporium/cshrp/howtos/howto.asp?hid=20

And I don’t know what this says exactly, but my issue is an international one [http://dobon.net/vb/dotnet/file/copyfolder.html]:


????????Directory.Move??????????????????”Directory.Copy”???????????????.NET Framework????????????????File.Copy????????????????????????


???????????????????(CopyDirectory????)??????????????????????????????


Aha!  This just in [from Kit George]: The .NET team is thinking about adding a Copy method to the System.IO.Directory class for Whidbey. http://weblogs.asp.net/bclteam/archive/2004/01/19/60377.aspx 

Comments (34)

  1. Grrr. .Text displays extended characters in the editor but not on the blog display page. Note to self: must note as SuggestedFeature in .Text wiki.

  2. Jeff says:

    I was gonna say… I saw a blog post a couple of weeks ago about this from someone on the theam and they gave the same answer. It does make sense, but certainly if you can ship something as complex as a DataGrid you can copy a directory. 🙂

  3. milbertus says:

    Could it have something to do with what Junfeng Zhang recently posted about (http://blogs.msdn.com/junfeng/archive/2004/02/20/76467.aspx)?

  4. Nick says:

    I had pretty much the same reaction when lookin for Directory.Rename() or File.Rename()

  5. My good friend Justin sends me another C# snippet to copy dirs recursively. Thanks Justin. Your copy()’s more elegant than my copy().;-)

    using System;

    using System.IO;

    namespace Utility.IO

    {

    public class Filesystem

    {

    // Copy directory structure recursively

    public static void copyDirectory(string src, string dst)

    {

    String[] files;

    if(dst[dst.Length-1]!=Path.DirectorySeparatorChar)

    dst+=Path.DirectorySeparatorChar;

    if(!Directory.Exists(dst)) Directory.CreateDirectory(dst);

    files=Directory.GetFilesystemEntries(src);

    foreach(string element in files)

    {

    // Sub directories

    if(Directory.Exists(element))

    copyDirectory(element,dst+Path.GetFileName(element));

    // files in directory

    else

    File.Copy(element,dst+Path.GetFileName(element),true);

    }

    }

    }

    }

  6. Joe Malaky says:

    Would the CopyFile API call do this more efficiently than the above code?

    http://www.webtropy.com/articles/art9-1.asp?f=CopyFile

  7. MoUsEM@H says:

    You have to add Reference from COM Object:

    "Microsoft Scripting Runtime"

    And then just use the following code:

    Private Sub CopyDir()

    Dim strSourcePath, strDestinationPath As String

    Dim mDirectory As New Scripting.FileSystemObject

    ‘parameter "True" means overwrite if exsts

    mDirectory.CopyFolder(strSourcePath, strDestinationPath, True)

    End Sub

  8. Rainer Trummel says:

    Of course, everybody used the Microsoft Scripting Runtime in VB6 to copy directories.

    but my first law : No COM in .NET !

    disallows me to use any COM in .NET 🙂 .

    So i will wait til Microsoft will include

    System.IO.Directory.Copy!

  9. Greg Arzoomanian says:

    What’s especially irritating is that the MS documentation explicitly states that the Directory class *does* provide a copy capability! From http://tinyurl.com/2r3ad:

    "Use the Directory class for typical operations such as *copying*, moving, renaming, creating, and deleting directories"

  10. Mark Davies says:

    Thank you Korby for the code. I have corrected a couple of minor case errors, and added a feature that allows the consumer of the function to choose whether or not to recursively copy the directory. Here it is.

    public static void CopyDirectory(string sourcePath, string destinationPath, bool recurse)

    // The calling function will need to handle the error if sourcePath cannot be found at runtime

    {

    String[] files;

    if (destinationPath[destinationPath.Length-1] != Path.DirectorySeparatorChar)

    destinationPath+=Path.DirectorySeparatorChar;

    if(!Directory.Exists(destinationPath)) Directory.CreateDirectory(destinationPath);

    files = Directory.GetFileSystemEntries (sourcePath);

    foreach(string element in files)

    {

    if (recurse)

    {

    // copy sub directories (recursively)

    if(Directory.Exists(element))

    CopyDirectory(element,destinationPath+Path.GetFileName(element), recurse);

    // copy files in directory

    else

    File.Copy(element,destinationPath+Path.GetFileName(element),true);

    }

    else

    {

    // only copy files in directory

    if(!Directory.Exists(element))

    File.Copy(element,destinationPath+Path.GetFileName(element),true);

    }

    }

    }

    Cheers

    Mark

    daviesma@qca.org.uk

  11. Jonathan Beeston says:

    I was looking for the same thing. Thank you for the code.

  12. Fred says:

    ‘ copy the entire contents of the C:DOCS directory into the

    ‘ C:BACKUPDOCS directory, overriding existing files.



    ‘ This code assumes that you added a reference to the

    ‘ Microsoft Scripting Runtime type library

    that is in the COM Project Reference

    Dim fso As New Scripting.FileSystemObject

    fso.CopyFolder "c:docs", "c:backupdocs", True

  13. CrazyScntst says:

    Here’s a slightly cleaner version of the code:

    public static void copyDirectory(DirectoryInfo srcPath, DirectoryInfo destPath, bool recursive)

    {

    if( !destPath.Exists )

    destPath.Create();

    // copy files

    foreach( FileInfo fi in srcPath.GetFiles() )

    {

    fi.CopyTo( Path.Combine(destPath.FullName, fi.Name), true );

    }

    // copy directories

    if( recursive )

    {

    foreach( DirectoryInfo di in srcPath.GetDirectories() )

    {

    copyDirectory( di, new DirectoryInfo( Path.Combine( destPath.FullName, di.Name ) ), recursive );

    }

    }

    }

  14. Stuart Jones says:

    Just wanted to say thanks; your efforts have saved me time! Nice work…

  15. jdk says:

    it works! thanks

  16. Thanks for the great tips about <a href="http://home-owner.kogaryu.com/black-jack-online-play.html"”>http://home-owner.kogaryu.com/black-jack-online-play.html" title="black jack online play">black jack online play</a> and [URL=http://home-owner.kogaryu.com/black-jack-online-play.html]black jack online play[/URL]

  17. Very informative post about <a href="http://debtin.50megs.com/cheap-loan-personal.html"”>http://debtin.50megs.com/cheap-loan-personal.html" title="cheap loan personal">cheap loan personal</a> and [URL=http://debtin.50megs.com/cheap-loan-personal.html]cheap loan personal[/URL]

  18. Thank you for this great post about <a href="http://winmoney.50megs.com/unsecured-loan-uk.html"”>http://winmoney.50megs.com/unsecured-loan-uk.html" title="unsecured loan uk">unsecured loan uk</a> and [URL=http://winmoney.50megs.com/unsecured-loan-uk.html]unsecured loan uk[/URL]

  19. Thank you so much for this great post  about <a href="http://getfreecredit.bravehost.com/debt-management-counseling.html"”>http://getfreecredit.bravehost.com/debt-management-counseling.html" title="debt management counseling">debt management counseling</a> and [URL=http://getfreecredit.bravehost.com/debt-management-counseling.html]debt management counseling[/URL]

  20. Yahzi says:

    I am looking for a solution for VC++ 6.0.

    While searching, I found someone actually arguing that DirectoryCopy _should not exist_. They pointed out all sorts of questions and problems.

    When you select a folder in Explorer and click "Copy," then "Paste," all of those problems are apparently solved.

    How can Microsoft justify requiring everyone, everywhere, to rewrite the same code again and again? This is why our country is going bankrupt. This is what is wrong with the economy. Microsoft should be tried for treason.

  21. phill says:

    Wondering myself where the hell Directory.Copy() is. That sucks ass.

    Now I got to write it myself, recursively 🙁

    ffs.

    Anyway thanks for the help guys.