开发者

Copy/extract part of a File path?

开发者 https://www.devze.com 2023-03-10 00:25 出处:网络
How can I copy/extract part of a File pat开发者_如何转开发h? For example, say if I have this path: D:\\Programs\\Tools\\Bin\\Somefile.dat

How can I copy/extract part of a File pat开发者_如何转开发h?

For example, say if I have this path: D:\Programs\Tools\Bin\Somefile.dat

how could I copy/extract it to make it like this:

C:\Users\Bin\Somefile.dat

or

C:\Users\Tools\Bin\Somefile.dat

or

C:\Users\Programs\Tools\Bin\Somefile.dat

Notice that the examples above are taking part of the original path, and changing it to another directory. I think this is called Expand name or something maybe??

PS, I already know about ExtractFileName and ExtractFilePath etc, the path anyway could be dynamic in that it wont be a hard coded path, but ever changing, so these functions are likely no good.

Thanks.


Here's a quick implementation that returns the TAIL of a path, including the specified number of elements. There's also a bit of demo of how to use it, and the results are exactly the ones you requested. Unfortunately I don't fully understand what transformations you're after: this might be exactly what you're after, or it might be something entirely wrong, that just happens to produce a result that looks like your sample:

program Project25;

{$APPTYPE CONSOLE}

uses
  SysUtils;

function ExtractPathTail(const OriginalPath:string; const PathElemCount:Integer):string;
var i, start, found_delimiters: Integer;
begin
  start := 0;
  found_delimiters := 0;
  for i:=Length(OriginalPath) downto 1 do
    if OriginalPath[i] = '\' then
    begin
      Inc(found_delimiters);
      if found_delimiters = PathElemCount then
      begin
        start := i;
        Break;
      end;
    end;
  if start = 0 then
    raise Exception.Create('Original path is too short, unable to cut enough elements from the tail.') // mangled English to help SO's code formatter
  else
    Result := System.Copy(OriginalPath, start+1, MaxInt);
end;

const SamplePath = 'D:\Programs\Tools\Bin\Somefile.dat';

begin
  try
    WriteLn('C:\Users\' + ExtractPathTail(SamplePath, 2)); // prints: C:\Users\Bin\Somefile.dat
    WriteLn('C:\Users\' + ExtractPathTail(SamplePath, 3)); // prints: C:\Users\Tools\Bin\Somefile.dat
    WriteLn('C:\Users\Programs\' + ExtractPathTail(SamplePath, 3)); // prints: C:\Users\Programs\Tools\Bin\Somefile.dat
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.


Have you looked at the ExtractFileName function? all built in for you. Depending on where your paths/files are coming from of course, you may need the ExtractFilePath, or other related functions.


try using the PathAppend and PathExtractElements functions

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号