整个目录的拷贝 Delphi TDirectory

自己的电脑上有些绿色软件,一般是放在D盘的一个目录下面,但是需要放在C盘使用,于是自己写了个拷贝或者更新的小程序练手。

IOUtils 单元主要就是三个结构: TDirectory、TPath、TFile, 很有用。这次我用到了TDirectory。

TDirectory.CreateDirectory();     {建立新目录}

TDirectory.Exists();              {判断文件夹是否存在}

TDirectory.IsEmpty();             {判断文件夹是否为空}

TDirectory.Copy();                {复制文件夹}

TDirectory.Move();                {移动文件夹}

TDirectory.Delete();              {删除文件夹, 第二个参数为 True 可删除非空文件夹}

TDirectory.GetDirectoryRoot();    {获取目录的根盘符, 如: C:\}

TDirectory.GetCurrentDirectory;   {获取当前目录}

TDirectory.SetCurrentDirectory(); {设置当前目录}

{这是实现拷贝一个目录的,源目录必须存在,目标目录如果存在,将重建。}
function CopyOnePath(sDirName:String;sToDirName:String):Boolean;
begin
  if not TDirectory.Exists(sDirName) then
  begin
   result:=false;
   exit;
  end;
  if TDirectory.Exists(sToDirName) then TDirectory.Delete(sToDirName,true);
  TDirectory.Copy(sDirName,sToDirName); {包括子目录在内,将全部复制。}
  result:=true;
end;

使用上面的系统函数,需要在头部包含:

uses
IOUtils;

以前曾用过下面的代码,留作参考。

function DoCopyDir(sDirName:String;sToDirName:String):Boolean;
var
   hFindFile:Cardinal;
   t,tfile:String;
   sCurDir:String[255];
   FindFileData:WIN32_FIND_DATA;
begin
   //记录当前目录
   sCurDir:=GetCurrentDir;
   ChDir(sDirName);
   hFindFile:=FindFirstFile('*.*',FindFileData);
   if hFindFile<>INVALID_HANDLE_VALUE then
   begin
        if not DirectoryExists(sToDirName) then
           ForceDirectories(sToDirName);
        repeat
              tfile:=FindFileData.cFileName;
              if (tfile='.') or (tfile='..') then
                 Continue;
              if FindFileData.dwFileAttributes=
              FILE_ATTRIBUTE_DIRECTORY then
              begin
                   t:=sToDirName+'\'+tfile;
                   if  not DirectoryExists(t) then
                       ForceDirectories(t);
                   if sDirName[Length(sDirName)]<>'\' then
                      DoCopyDir(sDirName+'\'+tfile,t)
                   else
                      DoCopyDir(sDirName+tfile,sToDirName+tfile);
              end
              else
              begin
                   t:=sToDirName+'\'+tFile;
                   CopyFile(PChar(tfile),PChar(t),True);
              end;
        until FindNextFile(hFindFile,FindFileData)=false;
      ///  FindClose(hFindFile);
   end
   else
   begin
        ChDir(sCurDir);
        result:=false;
        exit;
   end;
   //回到当前目录
   ChDir(sCurDir);
   result:=true;
end;
工作生活中,需要写个程序的时候就编个; 编写的过程中,需要用到的不会的就去网上搜个; 任务完成就好,不求闻达。
原文地址:https://www.cnblogs.com/sures/p/6013803.html