⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Copying a Folder with Subfolders and Files in C#

Always thought that .NET in System.IO had a method that implements folder copying with contents, including all subfolders and files. It turned out I was wrong, and there is no such method. Therefore, I bring an example of implementing this action using a fairly simple function with the help of System.IO.DirectoryInfo.

So, let's get to the point, here is the code with a detailed description of what and where it is done:


//begin_dir - директория источник.
//end_dir - директория приёмник.
void perebor_updates(string begin_dir, string end_dir)
        {
            //Берём нашу исходную папку
            DirectoryInfo dir_inf = new DirectoryInfo(begin_dir);
            //Перебираем все внутренние папки
            foreach (DirectoryInfo dir in dir_inf.GetDirectories())
            {
                //Проверяем - если директории не существует, то создаём;
                if (Directory.Exists(end_dir + "\\\\" + dir.Name) != true)
                {
                    Directory.CreateDirectory(end_dir + "\\\\" + dir.Name);
                }
                
                //Рекурсия (перебираем вложенные папки и делаем для них то-же самое).
                perebor_updates(dir.FullName, end_dir + "\\\\" + dir.Name);
            }

            //Перебираем файлики в папке источнике.
            foreach (string file in Directory.GetFiles(begin_dir))
            {
                //Определяем (отделяем) имя файла с расширением - без пути (но с слешем "\\").
                string filik = file.Substring(file.LastIndexOf(\'\\\\\'), file.Length - file.LastIndexOf(\'\\\\\'));
                //Копируем файлик с перезаписью из источника в приёмник.
                File.Copy(file, end_dir + "\\\\" + filik, true);
            }
        }



That's it.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.