Search code examples
delphidelphi-7subdirectory

Drive letter removed from path when retrieiving sub directories


I am trying to retrieve the subdirectories of a directory in delphi, I am using this function:

procedure GetSubDirectories(const directory : string; list : TStrings) ;
 var
   sr : TSearchRec;
 begin
   try
     if FindFirst(IncludeTrailingPathDelimiter(directory) + '*.*', faDirectory, sr) < 0 then
       Exit
     else
     repeat
       if ((sr.Attr and faDirectory <> 0) AND (sr.Name <> '.') AND (sr.Name <> '..')) then
         List.Add(IncludeTrailingPathDelimiter(directory) + sr.Name) ;
     until FindNext(sr) <> 0;
   finally
     SysUtils.FindClose(sr) ;
   end;
 end;

Then I tried something like:

procedure TForm1.FormCreate(Sender: TObject);
  var
    folders: TStringList;
  begin
    folders := TStringList.Create;
    try
      GetSubDirectories('c:\', folders);
      ShowMessage(folders.ValueFromIndex[0]);
    finally
      FreeAndNil(folders);
   end;
  end;

And the string shown in the messagebox is for example: ":\Program Files". I tried adding a breakpoitn on the List.Add in GetSubDirectories procedure and then the var looks like "C:\Program Files".

Why is the drive letter being removed in the message box?


Solution

  • ValueFromIndex requires you to use key-value pairs on TStringList what you're looking for is probably the Strings property of TStringList which is also the default propery of the class.

    So you could use folders[0] or folders.Strings[0]