What is the best way to recursively copy contents in C#?

What is the best way to recursively copy a folder’s content into another folder using C# and ASP.NET?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Well you can try this

DirectoryInfo sourcedinfo = new DirectoryInfo(@"E:source");
DirectoryInfo destinfo = new DirectoryInfo(@"E:destination");
copy.CopyAll(sourcedinfo, destinfo);

and this is the method that do all the work:

public void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    try
    {
        //check if the target directory exists
        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        //copy all the files into the new directory

        foreach (FileInfo fi in source.GetFiles())
        {
            fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
        }


        //copy all the sub directories using recursion

        foreach (DirectoryInfo diSourceDir in source.GetDirectories())
        {
            DirectoryInfo nextTargetDir = target.CreateSubdirectory(diSourceDir.Name);
            CopyAll(diSourceDir, nextTargetDir);
        }
        //success here
    }
    catch (IOException ie)
    {
        //handle it here
    }
}

I hope this will help 🙂

Method 2

Just use Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory in Microsoft.VisualBasic.dll assembly.

Add a reference to Microsoft.VisualBasic

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(source, destination);

Method 3

You can use SearchOption.AllDirectories to recursively search down folders, you just need to create the directories before you copy…

// string source, destination; - folder paths 
int pathLen = source.Length + 1;

foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories))
{
    string subPath = dirPath.Substring(pathLen);
    string newpath = Path.Combine(destination, subPath);
    Directory.CreateDirectory(newpath );
}

foreach (string filePath in Directory.GetFiles(source, "*.*", SearchOption.AllDirectories))
{
    string subPath = filePath.Substring(pathLen);
    string newpath = Path.Combine(destination, subPath);
    File.Copy(filePath, newpath);
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x