王宏健的专栏 ---- 健康快乐

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

删除目录,不管是空目录还是非空目录:

删除目录,不管是空目录还是非空目录:

function DoRemoveDir(sDirName:String):Boolean;
var
   hFindFile:Cardinal;
   tfile:String;
   sCurDir:String;
   bEmptyDir:Boolean;
   FindFileData:WIN32_FIND_DATA;
begin
   bEmptyDir:=True;
   sCurDir:=GetCurrentDir;
   SetLength(sCurDir,Length(sCurDir));
   ChDir(sDirName);
   hFindFile:=FindFirstFile('*.*',FindFileData);
   if hFindFile< >INVALID_HANDLE_VALUE then
   begin
        repeat
              tfile:=FindFileData.cFileName;
              if (tfile='.') or (tfile='..') then
              begin
                 bEmptyDir:=bEmptyDir and True;
                 Continue;
              end;
              bEmptyDir:=False;
              if FindFileData.dwFileAttributes=
              FILE_ATTRIBUTE_DIRECTORY then
              begin
                   if sDirName[Length(sDirName)]< >'\' then
                      DoRemoveDir(sDirName+'\'+tfile)
                   else
                      DoRemoveDir(sDirName+tfile);
                   if not RemoveDirectory(PChar(tfile)) then
                      result:=false
                   else
                      result:=true;
              end
              else
              begin
                   if not DeleteFile(PChar(tfile)) then
                      result:=false
                   else
                      result:=true;
              end;
        until FindNextFile(hFindFile,FindFileData)=false;
        FindClose(hFindFile);
   end
   else
   begin
        ChDir(sCurDir);
        result:=false;
        exit;
   end;
   if bEmptyDir then
   begin
        ChDir('..');
        RemoveDirectory(PChar(sDirName));
   end;
   ChDir(sCurDir);
   result:=true;
end;

function DeleteDir(sDirName:String):Boolean;
begin
      if Length(sDirName)< =0 then
         exit;
      Result:=DoRemoveDir(sDirName) and RemoveDir(sDirName);
end;

posted on 2005-05-13 10:26  LuckyJan  阅读(355)  评论(0)    收藏  举报