Search code examples
filedelphiwinapimove

Moving the content of a folder to another one


Using Delphi 7, I need to move all the content (files, folders and subfolders) from one folder to another one. After some research, SHFileOpStruct seems to be the best option. Here is what I got so far:

function MoveDir(SrcDir, DstDir: string): Boolean;
var
  FOS: TSHFileOpStruct;
begin
  ZeroMemory(@FOS, SizeOf(FOS));
  with FOS do
  begin
    wFunc  := FO_MOVE; // FO_COPY;
    fFlags := FOF_FILESONLY or
      FOF_ALLOWUNDO or FOF_SIMPLEPROGRESS;
    pFrom  := PChar(SrcDir + #0);
    pTo    := PChar(DstDir + #0);
  end;
  Result := (SHFileOperation(FOS) = 0);
end;

But when using this function, the entire folder is moved to destination, not only it content. For example, if I use MoveDir('c:\test', 'd:\test') I get d:\teste\teste.

I already tried to change this line bellow, and it works when coping the files (FO_COPY) but not when moving.

pFrom  := PChar(SrcDir + '\*.*' + #0);

Please, can someone help me with this? Would be great if I can do this without moving file by file, folder by folder...

Thanks!!


Solution

  • You should use your second version, without FOF_FILESONLY flag:

    function MoveDir(SrcDir, DstDir: string): Boolean;
    var
      FOS: TSHFileOpStruct;
    begin
      ZeroMemory(@FOS, SizeOf(FOS));
      with FOS do
      begin
        wFunc  := FO_MOVE; // FO_COPY;
        fFlags := FOF_ALLOWUNDO or FOF_SIMPLEPROGRESS;
        pFrom  := PChar(IncludeTrailingPathDelimiter(SrcDir) + '*.*'#0);
        pTo    := PChar(DstDir + #0);
      end;
      Result := (SHFileOperation(FOS) = 0);
    end;