While testing for property values (or the lack thereof) is how almost everything gets done in MSBuild, sometimes there are other ways.
How do you know whether the current MSBuild project is a SDK project?
In other words:
- given an XML file...
- whose full path is in the
MSBuildProjectFullPath
well-known property...
- and whose first tag is
Project
...
- does said tag have a
Sdk
attribute?
Thanks to MSBuild's property functions, you can do the following:
- use
[System.IO.File]::ReadAllText
to read the project file's contents as a string;
- then use
[System.Text.RegularExpressions.Regex]::IsMatch
to test for a Project
tag with a Sdk
attribute.
<PropertyGroup>
<_ProjectContents>$([System.IO.File]::ReadAllText(`$(MSBuildProjectFullPath)`))</_ProjectContents>
<_SdkRegex>(?s-i)(^|\s|>)<Project\s(([^>]*?)\s)?Sdk(\s*?)=(\s*?)"</_SdkRegex>
<_IsSdkProject>$([System.Text.RegularExpressions.Regex]::IsMatch(`$(_ProjectContents)`, `$(_SdkRegex)`))</_IsSdkProject>
</PropertyGroup>
Or, if you prefer a one-liner:
<PropertyGroup>
<_IsSdkProject>$([System.Text.RegularExpressions.Regex]::IsMatch(`$([System.IO.File]::ReadAllText(`$(MSBuildProjectFullPath)`))`, `(?s-i)(^|\s|>)<Project\s(([^>]*?)\s)?Sdk(\s*?)=(\s*?)"`))</_IsSdkProject>
</PropertyGroup>
Then you can use the value of _IsSdkProject
, which will be either True
OR False
, in a Condition
, like this:
<PropertyGroup Condition="'$(_IsSdkProject)'=='True'">
<SomeProperty>SomeValue</SomeProperty>
</PropertyGroup>
The regular expression explained
In the above regular expression, the <
and >
characters have been replaced with XML entities (<
and >
respectively). The original regex is as follows:
(?s-i)(^|\s|>)<Project\s(([^>]*?)\s)?Sdk(\s*?)=(\s*?)"
Which means:
- In single-line, case-sensitive mode...
- Either at the start of the file, or following a white-space character, or following a
>
character...
- find the literal string
<Project
...
- then a white-space character...
- then, optionally, any number of any character except
>
, and another white-space character...
- then the literal string
Sdk
...
- then, optionally, any number of white-space characters...
- then the character
=
...
- then, optionally, any number of white-space characters...
- then the character
"
A better explanation, together with an online tester where you can insert your project files' contents and test in real time, is on regex101.com. The site was made for Javascript regular expressions, which do not behave exactly like in .NET, but it is useful anyway.