Solved

To read contents of a folder

Posted on 2002-07-18
8
213 Views
Last Modified: 2010-04-04
Hello all,
Which object in Delphi can I use to read the contents of a folder and then loop thru all the files (of a specified type only)in the folder .I have to then read the contents of the files and save them to different tables.

Thanking in anticipation.
Pat.
0
Comment
Question by:Patranjali
8 Comments
 
LVL 7

Accepted Solution

by:
Cynna earned 100 total points
ID: 7161496
There is no object for this, but you could use following simple procedure:

procedure FilesInFolder(BaseDir, FileFilter: String; OutFullFileNames: TStrings);
var SR: TSearchRec;
    DosError: integer;
begin
   // Check if dir and filter are correct:
   if BaseDir[Length(BaseDir)]<>'\' then BaseDir:= BaseDir + '\';
   if Trim(FileFilter)='' then FileFilter:='*.*';
   // Find first file
   DosError := FindFirst(BaseDir+FileFilter, faAnyFile, SR);
   // Find all files in directory and place them in output list
   while DosError = 0 do begin
     if (SR.Attr <> faDirectory) then OutFullFileNames.Add(BaseDir+SR.Name);
     DosError := FindNext(SR);
   end;
   FindClose(SR);
end;

// DEMO:
// ----------
procedure TForm1.Button1Click(Sender: TObject);
begin
  // Add all text file names from C:\ to Memo1:
  FilesInFolder('C:\', '*.txt', Memo1.Lines);
end;
0
 

Author Comment

by:Patranjali
ID: 7161537
Thanks Cynna ,
I am looking into ur note.I have also discovered another way to do it.So lets see...

Pat

0
 
LVL 17

Expert Comment

by:Wim ten Brink
ID: 7165948
Short, but simple:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  SearchRec: TSearchRec;
begin
  if (FindFirst('*.*', faAnyFile - faDirectory, SearchRec) = 0) then begin
    repeat
      WriteLn('Doing something with ', SearchRec.Name);
    until (FindNext(SearchRec) <> 0);
    FindClose(SearchRec)
  end;
end.

One single application that's doing something with all files in the current folder. This is actually the preferred way to use FindFirst/FindNext/FindClose. Cynna already gave a correct answer but that method is out of date. It used to be valid but in an empty folder the FindClose might generate an error since FindFirst won't initialize and SearchRec structure. Also, Cynna's solution also adds folders and you want files only. (Thus, "faAnyFile - faDirectory"...)

Cynna was first however, thus give the points to Cynna. ;-)
0
 
LVL 7

Expert Comment

by:Cynna
ID: 7166875
Workshop_Alex,

I don't mean to split hair here, but i don't quite agree with your observations:

1. > ... but in an empty folder the FindClose might generate an error since FindFirst won't initialize and SearchRec structure...

Well, I took a quick glance at the RTL system library, and couldn't find this "error scenario":


function FindFirst(const Path: string; Attr: Integer;
  var F: TSearchRec): Integer;
const
  faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
begin
  F.ExcludeAttr := not Attr and faSpecial;
  F.FindHandle := FindFirstFile(PChar(Path), F.FindData);
  if F.FindHandle <> INVALID_HANDLE_VALUE then
  begin
    Result := FindMatchingFile(F);
    if Result <> 0 then FindClose(F);
  end else
    Result := GetLastError;
end;

procedure FindClose(var F: TSearchRec);
begin
  if F.FindHandle <> INVALID_HANDLE_VALUE then
  begin
    Windows.FindClose(F.FindHandle);
    F.FindHandle := INVALID_HANDLE_VALUE;
  end;
end;


So,

a) If FindFirst() sets INVALID_HANDLE_VALUE, FindClose code is ignored - no harm done.

b) Else, if FindFirst() gets FindMatchingFile(F)<>0, FindClose is called from it. Subsequent
   call to FindClose is redundant, however INVALID_HANDLE_VALUE flag is set, so it's back
   to case a).

If folder is empty FindFirstFile() will return INVALID_HANDLE_VALUE, ie. case a)
So I don't see how can this error be generated here, please correct me if I'm wrong...



2. > Also, Cynna's solution also adds folders and you want files only.

No it doesn't - please take a better look at my code, particularly the line:

> if (SR.Attr <> faDirectory) then OutFullFileNames.Add(BaseDir+SR.Name)


-----------

Now, after setting things straight, I must agree your code is more elegant - I just
copied fragments of some old code I had at hand - didn't spend time cleaning it up though.

> Cynna was first however, thus give the points to Cynna. ;-)

:) Thanks.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:Patranjali
ID: 7168943
Hello all,
Thanks for all you help.But I coulde solve the problem by
using a component called the FileListBox, which can be masked for specific files etc.
So I am  using that component.
Thanks,
Pat
0
 

Author Comment

by:Patranjali
ID: 7208466
Will someone please delete this question.
Thanks,
Pat
0
 

Expert Comment

by:CleanupPing
ID: 9343043
Patranjali:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 5

Expert Comment

by:Lukasz Lach
ID: 9461206
Patranjali,
No comment has been added lately (18 days), so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area for this question:

RECOMMENDATION: Award points to Cynna http:#7161496

Please leave any comments here within 7 days.

-- Please DO NOT accept this comment as an answer ! --

Thanks,

anAKiN
EE Cleanup Volunteer
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the…
Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now