Home > Blockchain >  Is there a simple way to copy a folder with its contents but without subfolders?
Is there a simple way to copy a folder with its contents but without subfolders?

Time:10-03

I am trying to make a application which is based around backing up data. I would like to add a option to copy a folder with its contents while ignoring the subfolders only.

I use TDirectory.Copy('C:\folder','C:\folder2'); to copy folders but that has no additional data requested other than the directory to copy and where to copy.

So, Is there a simple way to achieve this?

A function that can be called would work too.

CodePudding user response:

It's not perfect, but you could make your own routine based on this :

procedure TForm2.Button1Click(Sender: TObject);
var
  aSourceDir : String;
  aDestDir   : String;
  aFileList  : TStringDynArray;
  iFile      : Integer;
  aSourceFileName : String;
  aDestFileName   : String;
begin
  aSourceDir := 'C:\DEV\GitRepositories\TestProjects\WithStatementSample\';
  aDestDir   := 'C:\DEV\GitRepositories\TestProjects\WithStatementSample2\';

  aFileList := TDirectory.GetFiles( aSourceDir );

  if not ( TDirectory.Exists( aDestDir ) ) and
         ( Length( aFileList ) > 0 ) then
  begin
    TDirectory.CreateDirectory( aDestDir );
  end;

  for iFile := 0 to Pred( Length( aFileList ) ) do
  begin
    aSourceFileName := aFileList[ iFile ];
    aDestFileName   := IncludeTrailingPathDelimiter( aDestDir )  
                       ExtractFileName( aFileList[ iFile ] );

    TFile.Copy( aSourceFileName, aDestFileName );
  end;
end;

This will simply loop over every file found in the Source directory and copy it to the destination directory. It will not copy folders, nor copy contents of the folders.

Again, it's not 100% fool/bullet proof though, so you will have to adapt it to your needs if necessary.

  • Related