본문 바로가기

Program/Delphi

[Delphi] 재귀함수를 이용한 폴더 복사

재귀를 이용한 폴더 복사

pOverWrite 가 True이면 덮어쓰기, False이면 덮어쓰지 않고 건너감

// pSourceDir 폴더를 pDestinationDir 경로로 복사

// pSourceDir : 소스 디렉토리, pDestinationDir : 목적 디렉토리, pOverWrite : 덮어쓰기 유무

procedure CopyDirectoryAll(pSourceDir, pDestinationDir: string; pOverWrite: Boolean);

var

   TempList : TSearchRec;

begin

   if FindFirst(pSourceDir + '\*', faAnyFile, TempList) = 0 then

   begin

      if not DirectoryExists(pDestinationDir) then

         ForceDirectories(pDestinationDir);


      repeat

         if ((TempList.attr and faDirectory) = faDirectory) and not (TempList.Name = '.') and not (TempList.Name = '..') then

         begin

            if DirectoryExists(pSourceDir + '\' + TempList.Name) then

            begin

               CopyDirectoryAll(pSourceDir + '\' + TempList.Name, pDestinationDir + '\' + TempList.Name, pOverWrite);

            end;

         end

         else

         begin

            if not pOverWrite then

            begin

               if FileExists(pSourceDir + '\' + TempList.Name) then

               begin

                  CopyFile(pChar(pSourceDir + '\' + TempList.Name), pChar(pDestinationDir + '\' + TempList.Name), True);

               end;

            end

            else

            begin

               if FileExists(pSourceDir + '\' + TempList.Name) then

               begin

                  CopyFile(pChar(pSourceDir + '\' + TempList.Name), pChar(pDestinationDir + '\' + TempList.Name), False);

               end;

            end;

         end;

      until FindNext(TempList) <> 0;

   end;

end;