ASP.NET C# Copy Directory with SubDirectories with System.IO

前端 未结 3 668
醉酒成梦
醉酒成梦 2021-01-14 01:27

I need to copy a whole directory C:\\X to C:\\Y\\X, and I need the sub-folders to be copied as well.
Is there any way to do it with the System.IO.File\\Directory namespa

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 02:11

    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;
    
    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);
    }
    

提交回复
热议问题