delphi 修改文件夹名和文件名

时间:2021-08-13 08:13:14

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls,FileCtrl,ShellAPI;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
 countd,countf:integer;
 sum:integer;
implementation

{$R *.dfm}
//调用方法:ShellFileOperation(‘c:/afile.txt‘, ‘d:/afile2.txt‘, FO_COPY); FO_MOVE
procedure ShellFileOperation(fromFile: string; toFile: string; Flags: Integer);
var
  shellinfo: TSHFileOpStructA;
begin
   with shellinfo do
   begin
    wnd    := Application.Handle;
     wFunc := Flags;
     pFrom := PChar(fromFile);
     pTo    := PChar(toFile);
  end;
   SHFileOperation(shellinfo);
end;


// Example, Beispiel:

function   RenDirectory(const   OldName,NewName:string):   boolean;
  var
      fo:   TSHFILEOPSTRUCT;
  begin
      FillChar(fo,   SizeOf(fo),   0);
      with   fo   do
      begin
          Wnd   :=   0;
          wFunc   :=   FO_RENAME;
          pFrom   :=   PChar(OldName+#0);
          pTo   :=   pchar(NewName+#0);
          fFlags   :=   FOF_NOCONFIRMATION+FOF_SILENT;
      end;   
      Result   :=   (SHFileOperation(fo)   =   0);
  end; 

procedure   search(dir:string);   
  var   
      targetpath:string;{目标路径名}   
      sr:TsearchRec;   
    
  begin
      {第一阶段:找出初始dir目录下的所有文件,   
      其中dir变量值由edit1的Text属性确定}   
    
      targetpath:=extractfilepath(dir);{分解出目标路径名}   
      if   findfirst(dir,faanyfile,sr)=0   then
      repeat
        if((sr.name<>‘.‘)and(sr.name<>‘..‘){排除父目录和本目录两个假文件}   
        and((filegetattr(targetpath+sr.name)and   fadirectory)<>fadirectory)){只取文件}   
        then   
            begin
             sum:=sum+1;

RenameFile(targetpath+sr.name, targetpath+inttostr(sum));

countf:=countf+1;
            end
      until   findnext(sr)<>0;   
    
      if   findfirst(dir,faanyfile,sr)=0   then   
      repeat   
        if((sr.name<>‘.‘)and(sr.name<>‘..‘)){排除父目录和本目录两个假文件}   
        and((filegetattr(targetpath+sr.name)and   fadirectory)=fadirectory){排除文件}   
        then   
          begin
            sum:=sum+1;
            RenDirectory(targetpath+sr.name, targetpath+inttostr(sum));
            search(targetpath+inttostr(sum)+‘/*.*‘);{递归调用}
            //search(targetpath+sr.name+‘/*.*‘);{递归调用}

countd:=countd+1;   
          end
      until   findnext(sr)<>0;   
    
  end;