如何从改革后的路径中删除Windows驱动器刻字?德尔福或帕斯卡

Giz*_*eat 2 delphi freepascal conditional-compilation

这个回答的问题,我有另一个棘手的问题.我的编码是Free Pascal,但Delphi解决方案可能会起作用.

简而言之,我有一个串联路径的字符串值,它是通过获取源目录并在目标目录中重新创建该树而形成的.例如

C:\ SourceDir\SubDirA变为F:\ DestinationDir\SourceDir\SubDirA.

但是,我对我的程序的Linux版本的解决方案(如上面的链接中所述)与Windows版本不兼容,因为我最终得到:

F:\ DestionationDir\C:SourceDir\SubDirA.

这是无效的.

所以我想出了这个"仅在Windows中运行"代码来删除重组路径的中央驱动器号,但是在开头留下最初的一个,说"从左边的第4个字符开始查看字符串.如果你找到'C:',删除它",使路径变为F:\ DestinationDir\SourceDir\SubDirA.

{$IFDEF Windows} // Only do this for the Windows version
    k := posex('C:', FinalisedDestDir, 4);  // Find 'C:' in the middle of the concatanated path and return its position as k
    Delete(FinalisedDestDir, k, 2);  // Delete the 2 chars 'C:' of 'C:\' if found, leaving the '\' to keep the path valid
{$ENDIF}   
Run Code Online (Sandbox Code Playgroud)

现在,如果C:是所选目录的源,那就可以正常工作.但显然如果用户正在从另一个驱动器复制数据(例如E:,F:,G:或其他任何驱动器直到Z :)它将无法工作.

所以我的问题是,如何对其进行编码,使其显示"如果在左边第4个字符后找到任何驱动器号a:到z:,则将其删除"?虽然任何解决方案都"有效",但理想情况下我需要快速解决方案.最好的解决方案是首先没有它在那里,但鉴于我在回复我之前的帖子时发布的解决方案,由于我用来形成的程序,我无法弄清楚如何不使用它它.

kob*_*bik 6

这是我在我的应用程序中使用的代码:

function CombinePath(const BaseDir, Path: string): string;
begin
  if IsPathDelimiter(Path, 1) then
    Result := ExcludeTrailingBackSlash(BaseDir) + Path else
    Result := IncludeTrailingBackSlash(BaseDir) + Path;
end;

function MapRootPath(const Path, NewPath: string): string;
var
  Drive, RelativePath: string;
begin
  Drive := ExtractFileDrive(Path); // e.g: "C:"
  RelativePath := ExtractRelativePath(Drive, Path); // e.g: "Program Files\MyApp"
  Result := CombinePath(NewPath, RelativePath);
end;
Run Code Online (Sandbox Code Playgroud)

用法:

ShowMessage(MapRootPath('C:\SourceDir\SubDirA', 'F:\DestionationDir'));
// result is "F:\DestionationDir\SourceDir\SubDirA"
Run Code Online (Sandbox Code Playgroud)