Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

asp.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...