I'm trying to build my project from dotnet CLI.
I'm using dotnet build and it fails.
How to reproduce:
Create a simple console application using Visual Studio template
Add a file named Colors.txt to the solution directory
Add a file named Names.txt to the project directory
Modify csproj file to include a post-build event
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<Target Name="CopySettingsToOutput" AfterTargets="PostBuildEvent">
<Exec Command="copy $(ProjectDir)\Names.txt $(TargetDir)\Names.txt" />
<Exec Command="copy $(SolutionDir)\Colors.txt $(TargetDir)\Colors.txt" />
</Target>
Now build using Visual Studio (it gets built)
Now build using dotnet build command and it fails. It says:
error MSB3073: The command "copy *Undefined*\Colors.txt C:\\---path---\Colors.txt" exited with code 1.
Why is $(SolutionDir) undefined when using dotnet build?
The workaround is to provide that property in dotnet command like:
$slnPath = 'directory where is solution'
dotnet build -property:SolutionDir=$slnPath
That can be useful when you use dotnet in any build pipelines like Azure DevOps.
I think this question can help you: link
More details can be found in @Kamalpreet's answer.
To fix the problem, you can paste the following snippet into your Directory.Build.props file:
<Project>
<PropertyGroup>
<SolutionDir Condition="'$(SolutionDir)'==''">
$(MSBuildThisFileDirectory)
</SolutionDir>
</PropertyGroup>
</Project>
This approach is a bit different from another answer. It avoids passing -property:SolutionDir=... on every build by defining it once in Directory.Build.props, so it works automatically for all builds. Link is for context; the solution is summarized here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With