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

C# copy source directory files with original folder to the destination path

程序员文章站 2022-06-29 14:05:54
private static void PathCopyFilesWithOriginalFolder() { int sourceFilesNum = 0; try { string sourceDir = @"E:\Source"; string destDir = @"E:\Dest"; st... ......

 

private static void pathcopyfileswithoriginalfolder()
        {
            int sourcefilesnum = 0;
            try
            {                
                string sourcedir = @"e:\source";
                string destdir = @"e:\dest";
                string[] allsourcefiles = directory.getfiles(sourcedir, "*", searchoption.alldirectories);
                if (allsourcefiles != null && allsourcefiles.any())
                {
                    foreach (var sourcefilefullname in allsourcefiles)
                    {
                        string sourcefiledir = path.getdirectoryname(sourcefilefullname);
                        string sourcefilerelativedir = string.empty;
                        if (sourcefiledir.length > sourcedir.length)
                        {
                            sourcefilerelativedir = sourcefiledir.substring(sourcedir.length + 1);
                        }
                        else
                        {
                            sourcefilerelativedir = "";
                        }
                        string destfiledir = path.combine(destdir, sourcefilerelativedir);
                        if (!directory.exists(destfiledir))
                        {
                            directory.createdirectory(destfiledir);
                        }

                        string destfilefullname = path.combine(destfiledir, path.getfilename(sourcefilefullname));
                        file.copy(sourcefilefullname, destfilefullname, true);
                        string msg = $"sourcefilefullname:{sourcefilefullname},destfilefullname:{destfilefullname}";
                        console.writeline(msg);
                        sourcefilesnum++;
                    }
                }
            }
            catch(exception ex)
            {
                messagebox.show(ex.message);
            }
            finally
            {
                system.diagnostics.debug.writeline(sourcefilesnum);
            }            
        }