Link to home
Start Free TrialLog in
Avatar of ChLa
ChLaFlag for United States of America

asked on

is there a filepath shortening procedure ?

Is there an existing procedure that will shorten a filepath in a string by one level ? I would use it to implement an "Up one Level" button for a ShellFileView
For Example, D:\Images\Raccoons would become D:\Images
Avatar of jimyX
jimyX

There are many options actually.
There is a function that reads the folder path from the current filename "ExtractFileDir", so what I did is added a dummy extension to the folderpath and used that function so is stripes the filename and returns the parent directory:
procedure TForm1.Button1Click(Sender: TObject);
var
  s:string;
begin
  s:= 'D:\Images\Raccoons';
  if s[length(s)] = '\' then
    delete(s,length(s),1);
  showmessage(ExtractFileDir(s+'.ext'));
end;

Open in new window

A better way is to use copy function to copy the entire path up to the last "\" in the provided path:
procedure TForm1.Button1Click(Sender: TObject);
var
  Str:string;
begin
  Str := 'D:\Images\Raccoons\';
  if Str[length(Str)] = '\' then
    delete(Str,length(Str),1);           // to ensure the last slash in the path is for the parent directory
  showmessage(Copy(Str,1,LastDelimiter('\',Str)));
end;

Open in new window

I have read in About.com another way also you may see useful which using "ExpandFileName" and provide the parent directory indicator "\.." so it returns the path of the parent directory:
procedure TForm1.Button1Click(Sender: TObject);
var
  Str:string;
begin
 Str:= 'D:\Images\Raccoons\';
 Showmessage(ExpandFileName(Str + '\..'));
end;

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Bobcsi
Bobcsi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If you are using the FileSystemObject, you can use the ParentFolder property.
http://msdn.microsoft.com/en-us/library/dt64ftxb(v=vs.85).aspx
Avatar of ChLa

ASKER

Thank you for your help and quick response. I ended up using the solution from Bobcsi. I am sure others would have worked also and I learn from the information even if I didn't use it this time.
I used that solution because it looked the shortest and so I tried it first and it worked.
I used it to implement an up button for a ShellFileView. Here is that code:
ShellListView1.Root := (ExtractFilePath(ExcludeTrailingPathDelimiter(ShellListView1.RootFolder.PathName)));
Avatar of ChLa

ASKER

Thank You
Your welcome!