Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

To read contents of a folder

Posted on 2002-07-18
8
Medium Priority
?
220 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 7

Accepted Solution

by:
Cynna earned 400 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Suggested Courses

704 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