Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# copy all files in directory and subdirectories

  /// <summary>
        /// Copy all files in Directory and Sub Directory
        /// </summary>
        /// <param name="fromDir">Source Dir</param>
        /// <param name="toDir">Target Dir</param>
        /// <param name="includeSubDir">Sub Directory</param>
        /// <param name="overWrite">Overwrite exsiting files/folder if true</param>
        public static void Copy(string fromDir, string toDir, bool includeSubDir, bool overWrite)
        {
            if (string.IsNullOrEmpty(fromDir))
            {
                throw new ArgumentException($"'{nameof(fromDir)}' cannot be null or empty", nameof(fromDir));
            }


            DirectoryInfo dir = new DirectoryInfo(fromDir);
            DirectoryInfo[] directories = dir.GetDirectories();

            if (!Directory.Exists(toDir))
            {
                CreateDirectory(toDir);
            }

            var files = dir.GetFiles();
            foreach (var file in files)
            {
                var tmpPath = Path.Combine(toDir, file.Name);
                file.CopyTo(tmpPath, overWrite);

            }

            if (includeSubDir)
            {
                foreach (var subDir in directories)
                {
                    var tmpPath = Path.Combine(toDir, subDir.Name);
                    Copy(subDir.FullName, tmpPath, includeSubDir, overWrite);
                }
            }
        
        }
 
PREVIOUS NEXT
Tagged: #copy #files #directory #subdirectories
ADD COMMENT
Topic
Name
2+6 =