请问如何得到指定文件夹下所有.txt文件的文件名例如D:\Bak如何得到其下的所有.txt的文件名

解决方案 »

  1.   

    最简单的放一个FileListBox在窗体,然后设置:
    FileListBox1.Directory := 'D:\bak';
    FileListBox1.Mask := '*.txt';这时D:\bak\目录下所有的.txt文件就列到FileListBox中报。也可以用VCL中提供的FindFirst/FindNext或API:FindFirstFile/FindNextFile来枚举,Delphi的帮助中有FindFirst/FindNext的例子。
      

  2.   

    写函数:function SearchTxtFile(Path: string; var foundresult: TStrings): Boolean;
    var
      sr: TSearchRec;
      FileAttrs: Integer;
      sPath:string;
    begin
      FileAttrs := faAnyFile;  if FindFirst(Path+'\*.*', FileAttrs, sr) = 0 then
      begin
        repeat
          if ((sr.Name='.') or (sr.Name='..')) then
              Continue;      sPath :=  Path+'\'+sr.Name;//找到的文件或子目录      if (DirectoryExists(sPath)) then//查找子目录
               SearchTxtFile(sPath,foundresult);      if (ExtractFileExt(sr.Name) = '.txt') then
                foundresult.Add(sPath);
        until FindNext(sr) <> 0;
        FindClose(sr);
      end;
    end;调用示例:
    procedure TForm1.Button1Click(Sender: TObject);
    var
      sl:TStrings;
    begin
      sl := TStringList.Create;
      try
        SearchTxtFile('d:\bak',sl);
        Memo1.Lines := sl
      finally
        sl.Free
      end;
    end;