Restricting publish profiles can be achieved by including a build target in the .csproj (or .pubxml for web application) file for the project, as seen here. This will not force Visual Studio to only publish in the Release build config., but it will cause a failure if it is not run in Release build config.
For ClickOnce WinForms Project
I encountered a weird error where a directory could not be found when I redefined the `BeforePublish` target directly, so I made this run before it using `BeforeTargets`.
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...
<Target Name="ErrorWhenPublishingNotInReleaseMode" BeforeTargets="BeforePublish" Condition="'$(Configuration)' != 'Release'">
<Error Text="The application must only be published in the "Release" configuration." />
</Target>
</Project>
For .NET Framework Web Application
Add the following to the .pubxml file you publish with. The .csproj files don't seem to be used when publishing such a web application.
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...
<Target Name="AfterBuild" Condition="'$(Configuration)' != 'Release'">
<Error Text="The application must only be published in the "Release" configuration." />
</Target>
</Project>
Other available targets (<Target>
Name proprety) can be found here: https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-targets?view=vs-2019
A reference to how to use the Condition
property of the Target
tag can be found here: https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-conditions?view=vs-2019
I did find this other sort of relevant question, Can I force Visual Studio to use only a Release build configuration for my production publish profile?, but the question is too specific about other requirements and the selected answer is incorrect for my question.