Using MSBuild 4.0, is it possible to “simplify” a property containing a path?
-
28-10-2019 - |
Question
Suppose that I have a property containing
c:\workdir\project\wonder\subproj\..\..\common
and I want to reduce/simplify it to
c:\workdir\project\common
Furthermore, I would also like to be able to get a relative path from the current directory or specified.
Using the same starting property and having the current working directory set to
c:\workdir\project\wonder
I want it reduced to
..\common
Solution
The first part (resolving '..' in path) is relatively simple, you can do this using just property functions:
<PropertyGroup>
<Folder>c:\workdir\project\wonder\subproj\..\..\common</Folder>
</PropertyGroup>
<Message Text="Folder $(Folder)" />
<Message Text="Shortened path $([System.IO.Path]::GetFullPath($(Folder)))" />
Output:
Folder c:\workdir\project\wonder\subproj\..\..\common
Shortened path c:\workdir\project\common
The second part - shortening one path relatively to another - requires the use of a magical function Uri.MakeRelativeUri()
and wrapping it inside an inline task (or an external task library). Declare your task:
<UsingTask TaskName="RelativePath" TaskFactory="CodeTaskFactory"
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Target Required="true" />
<BaseDirectory Required="true" />
<Result Output="true" />
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs"><![CDATA[
Uri fromUri = new Uri(new DirectoryInfo(BaseDirectory).FullName
+ Path.DirectorySeparatorChar);
Uri toUri = new Uri(new DirectoryInfo(Target).FullName);
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
Result = relativeUri.ToString().Replace('/', Path.DirectorySeparatorChar);
]]></Code>
</Task>
</UsingTask>
Then use it as follows:
<PropertyGroup>
<Folder>c:\workdir\project\wonder\subproj\..\..\common</Folder>
<WorkingDir>c:\workdir\project\wonder</WorkingDir>
</PropertyGroup>
<Message Text="Folder $(Folder)" />
<Message Text="Base directory $(WorkingDir)" />
<RelativePath Target="$(Folder)" BaseDirectory="$(WorkingDir)">
<Output PropertyName="Relative" TaskParameter="Result"/>
</RelativePath>
<Message Text="Relative path $(Relative)" />
Output:
Folder c:\workdir\project\wonder\subproj\..\..\common
Base directory c:\workdir\project\wonder
Relative path ..\common
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow