by accident if any developer in team upgrade this package to 13.* then
we need to stop compilation of project in Visual Studio 2019 or 2022.
Could you please clarify about this accident? And in this situation, you can use the version range in csproj package reference to prevent this issue from happening:
References in project files (PackageReference)
For example:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="[10.0.1,12.0.3]" />
</ItemGroup>
</Project>
To parse the version the project actually using, I suggest using inline task or exec to parse the package version:
MSBuild inline tasks
Exec method
Both of these method can use code to parse json file obj\project.assets.json(Which stored package version info).
After getting the version, you can use the error task and condition to make the error and stop the build:
Error Task
If you want devops side solution, PMF's answer is another way.