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

 

你可能感兴趣的:(C# copy source directory files with original folder to the destination path)