欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# copy folder and files from source path to target path

程序员文章站 2022-08-08 15:13:58
static void Main(string[] args) { string sourceDir = @"E:\SourcePath"; string destDir = @"E:\Dest"; CopyDirectoriesFiles(sourceDir, destDir); Console.... ......
static void main(string[] args)
        {
            string sourcedir = @"e:\sourcepath";
            string destdir = @"e:\dest";
            copydirectoriesfiles(sourcedir, destdir);
            console.readline();       
        }

        public static void copydirectoriesfiles(string sourcedirectory, string targetdirectory)
        {
            var disource = new directoryinfo(sourcedirectory);
            var ditarget = new directoryinfo(targetdirectory);
            copyall(disource, ditarget);
        }

        public static void copyall(directoryinfo source, directoryinfo target)
        {
            directory.createdirectory(target.fullname);

            // copy each file into the new directory.
            foreach (fileinfo fi in source.getfiles())
            {
                console.writeline(@"copying {0}\{1}", target.fullname, fi.name);
                fi.copyto(path.combine(target.fullname, fi.name), true);
            }

            // copy each subdirectory using recursion.
            foreach (directoryinfo disourcesubdir in source.getdirectories())
            {
                directoryinfo nexttargetsubdir =
                    target.createsubdirectory(disourcesubdir.name);
                copyall(disourcesubdir, nexttargetsubdir);
            }
        }