How to dotnet build by wildcard pattern

Viewed 2041

I have .sln file which contains some projects in different folders, initially in root folder I have src and Tests folders and sln file. The structure is depicted on image below:

Solution structure

When I run dotnet build it builds all the projects. Another way is to pass <PROJECT | SOLUTION> file in order to build something more specific. I need to build only specific project according to the wildcard or exclude some projects from build.

When I try to pass **/src/*.csproj or !Tests/** it does not filter projects but gives the error from MSBuild:

Microsoft (R) Build Engine version 16.7.0+b89cb5fde for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

MSBUILD : error MSB1009: Project file does not exist.
Switch: **/src/*.csproj

Is there a way to build projects according to the wildcard pattern?

2 Answers

I couldn't find any parameters which could allow to build projects exactly by some pattern with dotnet build. It is possible to do so for dotnet test according to the reference.

In order to do something similar for dotnet build I could achieve what I wanted with powershell:

dir "*.csproj" -Recurse | %{dotnet build  $PSItem.FullName}

Having had a similar issue, I resorted to writing a batch file to help. In my solution, I wanted to pack all the libraries in my $(SolutionDir)\src folder, but nothing from $(SolutionDir)\tests, or $(SolutionDir)\tools.

$(SolutionDir)\pack.bat:

@echo off
for /D %%G in ("%cd%\%~1\*") DO (
    @echo %%~nxG
    dotnet build "%cd%\%~1\%%~nxG\%%~nxG.csproj" -c Release
    dotnet pack "%cd%\%~1\%%~nxG\%%~nxG.csproj" -o "%~2"  -c Release --include-symbols --include-source --no-build --no-restore
)

I've run an explicit build on each project, rather than rely on the implicit build. I found there were issues if the projects hadn't been built for a first time, they wouldn't be packed. It also ensures the build, because sometimes the implicit build cannot be run.

Usage:

You can use this within the Package Manager Console, with the following command.

./pack src .publish

This will pack all the projects within $(SolutionDir)\src, and the nuget packages will appear in $(SolutionDir)\.publish.

You can change the batch file to your liking, hardcoding variables if you want to, and making whatever changes you like to the commands. Whether you want to selectively build, publish, pack, or restore; this batch file gives a basic template for them all.

%cd% = Absolute current directory. %~1 = Relative directory to scan. %~2 = Relative output directory.

Related