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


 

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

 

posted @ 2019-12-04 11:15  FredGrit  阅读(404)  评论(1编辑  收藏  举报