Delphi中copy文件可否批量进行?(50分)

  • 主题发起人 主题发起人 若若
  • 开始时间 开始时间

若若

Unregistered / Unconfirmed
GUEST, unregistred user!
比如DOS中copy文件:copy c:/data/sj.* d:/bf/sj.*
在Delphi中有什么方法实行?
 
shfileOperation这个api就可以,具体你去Msdn吧
 
function CopyFiles(const Source,Dest: string): boolean;
var
fo: TSHFILEOPSTRUCT;
begin
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := 0;
wFunc := FO_COPY;
pFrom := @source[1];
pTo :=pchar(dest);
fFlags := FOF_NOCONFIRMATION+FOF_NOCONFIRMMKDIR ;
end;
Result := (SHFileOperation(fo) = 0);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
str:string;
i:integer;
begin
if opendialog1.Execute then
begin
for i:=0 to OpenDialog1.Files.Count-1 do
str:=str+OpenDialog1.Files.strings+#0;
showmessage(str);
str:=str+#0;
CopyFiles(str,'d:/temp');
end;
end;
 
CopyFiles直接可以用,为什么要写一个过程呢?
BOOL CopyFile(

LPCTSTR lpExistingFileName, // pointer to name of an existing file
LPCTSTR lpNewFileName, // pointer to filename to copy to
BOOL bFailIfExists // flag for operation if file exists
);
 
批量文件的拷贝,
将c:/tyn1下的所有文件拷贝到c:/tyn2下 :

procedure TForm1.Button1Click(Sender: TObject);
var
FileOpStruct :TSHFileOpStruct;
Buf1 :array [0..127] of Char;
Buf2 :array [0..127] of Char;
Str1,Str2 :String;
begin
Str1 :='c:/tyn1';
Str2 :='c:/tyn2';
FillChar(Buf1,SizeOf(Buf1),0);
FillChar(Buf2,SizeOf(Buf2),0);
StrPCopy(Buf1,Str1);
StrPCopy(Buf2,Str2);
with FileOpStruct do
begin
Wnd :=Handle;
wFunc :=FO_COPY;
pFrom :=@Buf1;
pTo :=@Buf2;
fFlags :=FOF_SIMPLEPROGRESS;
fAnyOperationsAborted :=False;
hNameMappings :=nil;
lpszProgressTitle :='拷贝文件';
end;
SHFileOperation(FileOpStruct);
end;

记得添加ShellAPI单元。
 
对,用这个函数就行,可以拷贝多个文件
这个函数还可以重命名,删除等等
 
procedure CopyDirectoryTree(AHandle: THandle; const AFromDirectory, AToDirectory: String);
var
SHFileOpStruct: TSHFileOpStruct;
FromDir: PChar;
ToDir: PChar;
begin

GetMem(FromDir, Length(AFromDirectory)+2);
try
GetMem(ToDir, Length(AToDirectory)+2);
try

FillChar(FromDir^, Length(AFromDirectory)+2, 0);
FillChar(ToDir^, Length(AToDirectory)+2, 0);

StrCopy(FromDir, PChar(AFromDirectory));
StrCopy(ToDir, PChar(AToDirectory));

with SHFileOpStruct do
begin
Wnd := AHandle; // Assign the window handle
wFunc := FO_COPY; // Specify a file copy
pFrom := FromDir;
pTo := ToDir;
fFlags := FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION;
fAnyOperationsAborted := False;
hNameMappings := nil;
lpszProgressTitle := nil;
if SHFileOperation(SHFileOpStruct) <> 0 then
RaiseLastWin32Error;
end;
finally
FreeMem(ToDir, Length(AToDirectory)+2);
end;
finally
FreeMem(FromDir, Length(AFromDirectory)+2);
end;
end;
 
后退
顶部