Solved

To read contents of a folder

Posted on 2002-07-18
8
214 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

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…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

863 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

28 Experts available now in Live!

Get 1:1 Help Now