一个方法获取一个目录下的所有文件和文件夹。。。。。。。

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    btn1: TButton;
    lst_file: TListBox;
    lst_path: TListBox;
    lbl1: TLabel;
    lbl2: TLabel;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }       {全局变量,其他单元不能访问}

  public
    { Public declarations }         {全局变量,其他单元能访问}
  end;

var {全局变量,其他单元能访问}
  Form1: TForm1;
    stringfiles:TStrings; //用来保存搜到的文件
    stringpath:TStrings;  //用来保存搜到的文件夹
implementation
{全局变量,其他单元能访问}
{$R *.dfm}
{全局变量,其他单元不能访问}
function issondir(searchrec:TSearchRec):Boolean; //判断是否为文件夹
begin
  if (searchrec.Attr=16) and (searchrec.Name<>'.') and (searchrec.Name<> '..') then
    Result:=True else Result:=False;

end;

function getsubfileandsundir(mainpath:string):string;   //获取文件和文件夹
var
  i:Integer;
  searchrec:TSearchRec;
  searchpath:TStrings; //用来临时储存搜到的文件夹,因为该方法的每一次递归,该变量必须重新初始化,用来储存下一轮递归搜到的文件夹   。。。这里不能用全局变量,这样会导致子程序不停地引用而导致报错
begin
   searchpath:=TStringList.Create;
   if(FindFirst(mainpath+'\*.*',faAnyFile,searchrec)=0) then
   begin
     if issondir(searchrec) then
     begin
        searchpath.Add(searchrec.Name);
     end
     else
     begin
         if (searchrec.Name<>'.') and (searchrec.Name<> '..') then
          stringfiles.Add(searchrec.Name);
     end;
     while FindNext(searchrec)=0 do
     begin
       if issondir(searchrec) then searchpath.Add(searchrec.Name)
       else
        begin
         if (searchrec.Name<>'.') and (searchrec.Name<> '..') then
          stringfiles.Add(searchrec.Name);
         end;
     end;
     FindClose(searchrec);

     for i:=0 to searchpath.Count-1 do
     begin
         stringpath.Add(searchpath[i]);
         getsubfileandsundir(mainpath+'\'+searchpath[i]); //这个参数里面的mainpath非整个方法的mainpath。。因为程序用的是递归,如果将程序还原,即将递归解开,那就相当于将
                              //该方法下的所有代码一遍又一遍的重复在下面,这样就清楚了,程序递归表面看来是循环执行,其实是自上而下的不断执行子程序,那么这样,程序中申明
                              //的变量将不是原来的变量,因为自上而下重新初始化了一遍,所以不用担心这里的mainpath会与方法的参数mainpath混淆
     end;
      searchpath.Free;//释放资源
   end;
end;


procedure TForm1.btn1Click(Sender: TObject);   //按钮点击事件
var
  c:Integer;
  d:Integer;
begin
  stringfiles:=TStringList.Create;
  stringpath:=TStringList.Create;
  getsubfileandsundir('C:\Documents and Settings\Administrator\桌面\99');
  for c:=0 to (stringfiles.Count-1) do
  begin
     lst_file.Items.Add(stringfiles[c]);
  end;

  for d:=0  to stringpath.Count-1  do
  begin
     lst_path.Items.Add(stringpath[d]);
  end;

  stringfiles.Clear;  // 清空数组
  stringpath.Clear;

  lst_file.Items.Clear;  //清空listbox
  lst_path.Items.Clear;
 
end;

end.

posted @ 2012-09-27 22:04  斗天!  阅读(351)  评论(0编辑  收藏  举报