我的最终目标是将所有相关文件从一个文件夹复制到另一个文件夹。因此,例如,我们有C:\Users\Tool\Desktop\test\oldStuff
。在该文件夹中,oldStuff
我们有更多文件夹以及一些mp3,mp4和txt文件。
现在,我想将所有小于GB的mp4文件复制到C:\Users\Tool\Desktop\test\New_Stuff_Less_than_a_Gig
,并将大于GB的.mp4文件复制到C:\Users\Tool\Desktop\test\New_STuff_Bigger_than_a_Gig
。
我虽然这很容易,但是我错了。到目前为止,不需要担心文件类型,所以就做到了*.*
procedure TForm4.Button1Click(Sender: TObject);
var
f: TSearchRec;
Dir: string;
begin
if not SelectDirectory(Dir,widestring(Dir),Dir) then Exit;
FileMode:=0;
if FindFirst(Dir+'\*.*',faAnyFile,f) = 0 then
repeat
try
if (f.Attr and faDirectory ) < $00000008 then
CopyFile(PChar(Dir+'\'+f.Name),PChar
('C:\Users\Tool\Desktop\test\new\'+f.Name),false);
except
on e: exception do
ShowMessage(E.Message);
end;
until findNext(f) <> 0
end;
它将复制所选文件夹中的任何内容,但不会复制所选文件夹中的文件夹中的任何内容。例如,如果有C:\Users\Tool\Desktop\test\oldStuff\movie.mp4
,它将复制Movie.mp4
文件,但如果有C:\Users\Tool\Desktop\test\oldStuff\movies\Movie.mp4
,将不会复制Movie.mp4
文件。我虽然可以做这样的事情
CopyFile.size < 1000 (PChar('C:\Users\Tool\Desktop\test\oldStuff\*.*'+f.Name),
PChar('C:\Users\Tool\Desktop\test\new_Stuff\'+f.Name),false)
甚至只是
CopyFile (PChar('C:\Users\Tool\Desktop\test\old\*.*'+f.Name),
PChar('C:\Users\Tool\Desktop\test\new\'+f.Name),false);
但它没有复制任何内容。
这是一个示例(在XE7中完成),可以完成您想要的操作。显然,您需要对其进行修改以适合您的需求;它具有硬编码的路径信息和文件掩码(* .png),并使用常数来确定文件的大小。
它基于以下示例目录树:
D:\TempFiles
|--\Test
|-----\A
|-----\B
|--------\SubB
|-----\NewFiles
|-------\Large
L-------\Small
它找到D:\ TempFiles \ Test及其子文件夹中的所有.png文件,并将等于或大于10KB的文件复制到D:\ TempFiles \ NewFiles \ Large,将小于10KB的文件复制到D:\ TempFiles \ NewFiles \ Small。
您需要将IOUtils
和添加Types
到实现uses
子句中。
procedure TForm1.Button1Click(Sender: TObject);
var
aLargeFiles: TStringDynArray;
aSmallFiles: TStringDynArray;
const
LargeSize = 10 * 1024;
SourcePath = 'D:\TempFiles\Test\';
begin
aLargeFiles := TDirectory.GetFiles(SourcePath, '*.png',
TSearchOption.soAllDirectories,
function (const Path: string; const SR: TSearchRec): Boolean
begin
Result := (SR.Size >= LargeSize);
end);
aSmallFiles := TDirectory.GetFiles(SourcePath, '*.png',
TSearchOption.soAllDirectories,
function(const Path: string; const SR: TSearchRec):Boolean
begin
Result := (SR.Size < LargeSize);
end);
CopyFilesToPath(aLargeFiles, 'D:\TempFiles\NewFiles\Large\');
CopyFilesToPath(aSmallFiles, 'D:\TempFiles\NewFiles\Small\');
end;
procedure TForm1.CopyFilesToPath(aFiles: array of string; DestPath: string);
var
InFile, OutFile: string;
begin
for InFile in aFiles do
begin
OutFile := TPath.Combine( DestPath, TPath.GetFileName( InFile ) );
TFile.Copy( InFile, OutFile, True);
end;
end;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句