2006. május 29., hétfő

How to copy all files from one directory to another


Problem/Question/Abstract:

Creating a new directory (folder) is no problem. There is the MkDir() procedure. But how does one copy all files from another directory into this new one within Delphi run time? I am also concerned that any pseudo DOS command will not be available in the future, especially Windows NT 5 (2000).

Answer:

Solve 1:

uses
  shellapi

function FileManager(xSourcePath, xDestPath, xPara: string): Boolean;
var
  PFileMsg: TSHFileOpStruct;
  mNowPath: string;
begin
  Result := False;
  FillChar(PFileMsg, sizeof(PFileMsg), #0);
  if pos('.', xpara) = 0 then
    exit;
  mNowPath := GetCurrentDir;
  if xSourcePath <> '' then
    if not DirectoryExists(xSourcePath) then
    begin
      showmessage('The source path does not exist !');
      exit;
    end;
  if xDestPath <> '' then
    if not DirectoryExists(xDestPath) then
    begin
      showmessage('The destination path does not exist !');
      exit;
    end;
  if SetCurrentDirectory(Pchar(xSourcePath)) then
  begin
    with PFileMsg do
    begin
      if Owner is TForm then
        Wnd := TForm(Owner).Handle
      else
        Wnd := Application.Handle;
      if xDestPath <> '' then
      begin
        wFunc := FO_COPY;
        PTo := pChar(xDestPath);
        fFlags := FOF_MULTIDESTFILES + FOF_NOCONFIRMATION;
      end
      else
      begin
        wFunc := FO_DELETE;
        fFlags := FOF_ALLOWUNDO + FOF_NOCONFIRMATION;
      end;
      pFrom := PChar(xPara + #0#0);
    end;
    SHFileOperation(PFileMsg);
    SetCurrentDirectory(Pchar(mNowPath));
    Application.ProcessMessages;
    Result := True;
  end;
end;


Example:

CopyFile:
FileManager('C:\Demo', 'C:\Temp', '*.*');

DeleteFile: (delete C: \Demo\ * . * )
FileManager('C:\Demo', '', '*.*');


Solve 2:

uses
  ShellAPI;

procedure TForm1.BtnCopyClick(Sender: TObject);
var
  fileOp: TShFileOpStruct;
  fromDir: string;
  toDir: string;
begin
  FillChar(fileOp, Sizeof(TShFileOpStruct), 0);
  fromDir := DirectoryListBox1.Directory + '\*.*'#0;
  toDir := DirectoryListBox2.Directory + #0;
  with fileOp do
  begin
    wnd := Handle;
    wfunc := FO_COPY;
    pFrom := PChar(fromDir);
    pTo := PChar(toDir);
    fFlags := FOF_ALLOWUNDO;
    fAnyOperationsAborted := false;
    hNameMappings := nil;
    lpszProgressTitle := nil;
  end;
  SHFileOperation(fileOp);
end;

Nincsenek megjegyzések:

Megjegyzés küldése