Home > Software design >  Vary the build output path depending on the current OS
Vary the build output path depending on the current OS

Time:01-17

I'm currently working on my first .NET 6 cross-plattform project in VisualStduio 2022. I want to change my build output (Base output path) to: ..\..\..\bin\. I know that this only works for windows. Is there a way to adjust this path so it works for both windows and unix?

I tried this and it only works for windows:

<PropertyGroup>
  <IsWindows Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Windows)))' == 'true'">true</IsWindows>
  <IsLinux Condition="'$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' == 'true'">true</IsLinux>
</PropertyGroup>

<PropertyGroup Condition="'$(IsWindows)'=='true'">   
  <BaseOutputPath>..\..\..\bin\</BaseOutputPath>
</PropertyGroup>

<PropertyGroup Condition="'$(IsLinux)'=='true'">
  <BaseOutputPath>../../../bin/</BaseOutputPath>
</PropertyGroup>

In my project.cs I would use:

System.IO.Directory.GetParent(System.Environment.CurrentDirectory).Parent.FullName;

but not sure how to use it in the xml

CodePudding user response:

MSBuild v15 and later has a NormalizeDirectory function that will ensure the correct directory separator for the current OS. (See "MSBuild property functions".) Your code can be changed to the following:

  <PropertyGroup>
    <BaseOutputPath>$([MSBuild]::NormalizeDirectory('..\..\..\bin\'))</BaseOutputPath>
  </PropertyGroup>

In ItemGroups, MSBuild handles mapping paths based on the OS. In the following example the Include paths are equivalent, interchangeable, and work on both Windows and Unix.

    <ItemGroup>
      <Windows Include="..\..\..\bin\*.*" />
      <Unix    Include="../../../bin/*.*" />
    </ItemGroup>

If for other reasons you need to know the current OS is Unix, use the IsOSUnixLike function.

    <Message Text="Hello Windows" Condition="!$([MSBuild]::IsOSUnixLike())" />
    <Message Text="Hello *nix"    Condition="$([MSBuild]::IsOSUnixLike())" />
  • Related