MSBuild:如何获取文件的相对路径,给定一个绝对路径
本文关键字:路径 一个 何获取 获取 MSBuild 文件 相对 | 更新日期: 2023-09-27 18:35:12
我有一个情况,我有一堆绝对路径,我想使用 MSBuild 将它们转换为基于另一个目录的相对路径。这是我到目前为止的代码:
<PropertyGroup>
<FromPath>$(Bar)</FromPath>
</PropertyGroup>
<ItemGroup>
<AbsolutePaths Include="@(Foo)" Exclude="@(Baz)" />
<PathsRelativeToBar Include="@(AbsolutePaths->'???')" /> <!-- What goes here? -->
</ItemGroup>
任何帮助将不胜感激,谢谢!
编辑:我在这个 StackOverflow 问题中找到了一个基于 C# 的解决方案,但我不确定如何(或是否可能)将其转换为 MSBuild。
MSBuild 中有一个名为"MakeRelative"的本机函数。
以下是使用它的方法。
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.5" >
<PropertyGroup>
<Bar>c:'temp'msbuild-sample'2</Bar>
<FromPath>$(Bar)</FromPath>
</PropertyGroup>
<ItemGroup>
<AbsolutePaths Include="c:'temp'msbuild-sample'1'**'*.txt" />
</ItemGroup>
<Target Name="Build">
<ItemGroup>
<PathsRelativeToBar Include="@(AbsolutePaths)">
<!-- Here is the magic... we're adding a piece of metadata with the relative path -->
<RelativePath>$([MSBuild]::MakeRelative($(FromPath), %(AbsolutePaths.FullPath)))</RelativePath>
</PathsRelativeToBar>
</ItemGroup>
<Message Text="----- Absolute paths -----" />
<Message Text="%(AbsolutePaths.FullPath)" />
<Message Text="----- Relative paths (showing full path) -----" />
<Message Text="%(PathsRelativeToBar.FullPath)" />
<Message Text="----- Relative paths (relative to $(FromPath)) -----" />
<Message Text="%(PathsRelativeToBar.RelativePath)" />
</Target>
</Project>
以下是我当前环境的快速视图
C:'temp'msbuild-sample>dir /s /b
C:'temp'msbuild-sample'1
C:'temp'msbuild-sample'sample.build
C:'temp'msbuild-sample'1'1.1
C:'temp'msbuild-sample'1'1.txt
C:'temp'msbuild-sample'1'2.txt
C:'temp'msbuild-sample'1'1.1'3.txt
C:'temp'msbuild-sample'1'1.1'4.txt
这是输出。
----- Absolute paths -----
c:'temp'msbuild-sample'1'1.1'3.txt
c:'temp'msbuild-sample'1'1.1'4.txt
c:'temp'msbuild-sample'1'1.txt
c:'temp'msbuild-sample'1'2.txt
----- Relative paths (showing full path) -----
c:'temp'msbuild-sample'1'1.1'3.txt
c:'temp'msbuild-sample'1'1.1'4.txt
c:'temp'msbuild-sample'1'1.txt
c:'temp'msbuild-sample'1'2.txt
----- Relative paths (relative to c:'temp'msbuild-sample'2) -----
..'1'1.1'3.txt
..'1'1.1'4.txt
..'1'1.txt
..'1'2.txt
希望这对:)有所帮助