在这两种方式中组合路径有什么区别?

pen*_*ake 2 .net powershell

你能解释一下它们之间的区别吗?

$attachment = [String]::Concat($workingDir,"\", $fileName)
Run Code Online (Sandbox Code Playgroud)

和

$attachment = [IO.Path]::Combine($workingDir, $fileName)
Run Code Online (Sandbox Code Playgroud)

在Powershell中组合路径时?

Ans*_*ers 11

考虑$workingDir具有尾随反斜杠且$fileName具有前导反斜杠的情况,例如:

$workingDir = "C:\foo\"
$fileName   = "\bar.txt"
Run Code Online (Sandbox Code Playgroud)

2个命令将产生以下结果:

PS C:\> [String]::Concat($workingDir, "\", $fileName)
C:\foo\\\bar.txt
PS C:\> [IO.Path]::Combine($workingDir, $fileName)
\bar.txt

在PowerShell中,最好使用Join-Path:

PS C:\> Join-Path $workingDir $fileName
C:\foo\bar.txt