Bulk Updating .NET Framework Versions In Legacy Projects With Powershell

For one of our customers, I recently had to change the target .NET Framework version from 4.5.1 to 4.6.1 because a new version of some important Nuget package requires .NET 4.6.1. Changing the framework version in newer SDK-based projects is not a problem but the old csproj files, the big ones with the packages.config file, need some special treatment.

In diesem Artikel:

Bulk Updating .NET Framework Versions In Legacy Projects With Powershell
Pawel Gerr ist Architekt und Consultant bei Thinktecture. Er hat sich auf .NET Core Backends spezialisiert und kennt Entity Framework von vorne bis hinten.

The required steps are:

  1. Update the TargetFrameworkVersion to v4.6.1 in all csproj files.
  2. Use the Package Manager Console in Visual Studio to re-install the Nuget packages without increasing the version of installed packages. This Package Manager Console is a special one providing us with some PowerShell commands that are not available otherwise. We need to re-install the Nuget packages because it…

    • updates the target framework version in the packages.config
    • adjusts the (package) reference in case the Nuget package has different DLLs for different .NET versions
    • runs PowerShell scripts if the Nuget package has any
    • updates the assembly bindings in app.config / web.config

You can work on these tasks manually if you are only dealing with a dozen projects and a few solutions files, but it is not practical with 40 solutions containing over 300 projects. Furthermore, there might be plans to test the applications with higher .NET versions, like 4.7.2, in that case, we might have to do all the steps multiple times.

Update the TargetFrameworkVersion

I am using a PowerShell script to find all project files (*.csproj) and update the TargetFrameworkVersion.

First, we need to find all project files starting from the repository root (e.g. C:\Projects\MyLegacyProject).

				
					using namespace System.Collections.Generic # for List<T> 

$dir = "." # points to "repository root"
$targetFrameworkVersion = [Version]::new("4.6.1")

$projFiles = Get-ChildItem $dir -Recurse -Filter *.csproj

				
			

Next, we fetch the content of each project file and extract the current framework version. All the information is saved in a custom object.

				
					$projsWithVersion = [List[object]]::new()

foreach($file in $projFiles)
{
    $content = [xml](Get-Content $file.FullName)
    $versionNodes = $content.GetElementsByTagName("TargetFrameworkVersion");
        
    switch($versionNodes.Count)
    {
        0 {
            Write-Host "The project has no framework version: $file.FullName"
            break;
        }
        1 {
            $version = $versionNodes[0].InnerText;

            $projsWithVersion.Add([PsCustomObject]@{
                File = $file;
                XmlContent = $content;
                VersionNode = $versionNodes[0];
                VersionRaw = $version;
                Version = [Version]::new($version.Replace("v", ""))
            })
            break;
        }
        default {
            Write-Host "The project has multiple elements of TargetFrameworkVersion: $file.FullName"
            break;
        }
    }
}
				
			

If you want to know how many projects are referencing what version then you can call the following function.

				
					function Print-Version-Statistics([List[object]] $projsWithVersion)
{
    $numberOfProjectsByVersion = @{}

    foreach($proj in $projsWithVersion)
    {
        if($numberOfProjectsByVersion.ContainsKey($proj.Version))
        {
            $numberOfProjectsByVersion[$proj.Version] = $numberOfProjectsByVersion[$proj.Version] + 1
        }
        else
        {
            $numberOfProjectsByVersion[$proj.Version] = 1
        }
    }
    
    Write-Host "`nCurrent version distribution:"
    $numberOfProjectsByVersion
}
				
			

The next PowerShell fragment is updating the TargetFrameworkVersion if the current version is less than 4.6.1.

				
					foreach($proj in $projsWithVersion)
{    
    if($targetFrameworkVersion.CompareTo($proj.Version) -gt 0)
    {
        $proj.VersionNode.set_InnerXML("v$targetFrameworkVersion")
        $proj.XmlContent.Save($proj.File.FullName);
    }
}
				
			

Re-install all Nuget Packages

After the execution of the script all csproj files are targeting .NET 4.6.1. Lastly you need to run the command Update-Package -reinstall in the Package Manager Console in Visual Studio but there is an issue. I neither have a solution referencing all projects, nor do I want to open 40 solutions. Let’s extend our previous PowerShell script so it creates a new solution with all projects in it.For that, we will use the dotnet (core) CLI.

				
					$slnName = "AllProjects" # name without file extension
$slnFilePath = Join-Path $dir ($slnName + ".sln")

dotnet new sln -o $dir -n $slnName # creates new sln-file

foreach($proj in $projsWithVersion)
{
    # adds the project to solution
    # filter out unchanged projects if needed
    dotnet sln $slnFilePath add $proj.File.FullName
}
				
			

But before executing the script, we need to do something. Otherwise, dotnet CLI will raise an error because of missing MsBuild tasks. Usually, the old projects are referencing some Visual-Studio-specific MsBuild tasks that do not come with the .NET Core SDK.

On my machine, I have Visual Studio 2019 installed, so the MsBuild tasks are in folder C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Microsoft\VisualStudio. Currently, my .NET Core SDK is 3.1.200 so the CLI is searching for MsBuild tasks in C:\Program Files\dotnet\sdk\3.1.200\Microsoft\VisualStudio which does not exist. If you are using a different version of Visual Studio or SDK then you have to adjust the folder paths accordingly.
To make the CLI happy, we have to copy the whole folder C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Microsoft\VisualStudio to C:\Program Files\dotnet\sdk\3.1.200\Microsoft. Alternatively, instead of copying the folder, you can create a symbolic link.

After letting the script run, we should have a new AllProjects.sln. What you still need to do is to open the solution in Visual Studio and execute Update-Package -reinstall in the Package Manager Console. Depending on the number of projects it could take several minutes to complete.

Summary

After working with SDK-based projects, the older projects feel quite inconvenient. The amount of work I showed you in this article is actually not necessary with newer projects. In that case, you neither need PowerShell nor Visual Studio to update a version, a Directory.Build.props/Directory.Build.targets files usually are more than enough to apply changes to multiple projects.

Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Diese Artikel könnten Sie interessieren
.NET
Incremental Roslyn Source Generators: High-Level API – ForAttributeWithMetadataName – Part 8

Incremental Roslyn Source Generators: High-Level API – ForAttributeWithMetadataName – Part 8

With the version 4.3.1 of Microsoft.CodeAnalysis.* Roslyn provides a new high-level API - the method "ForAttributeWithMetadataName". Although it is just 1 method, still, it addresses one of the biggest performance issue with Source Generators.
16.05.2023
.NET
Integrating AI Power into Your .NET Applications with the Semantic Kernel Toolkit – an Early View

Integrating AI Power into Your .NET Applications with the Semantic Kernel Toolkit – an Early View

With the rise of powerful AI models and services, questions come up on how to integrate those into our applications and make reasonable use of them. While other languages like Python already have popular and feature-rich libraries like LangChain, we are missing these in .NET and C#. But there is a new kid on the block that might change this situation. Welcome Semantic Kernel by Microsoft!
03.05.2023
.NET
.NET 7 Performance: Regular Expressions – Part 2

.NET 7 Performance: Regular Expressions – Part 2

There is this popular quote by Jamie Zawinski: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems."

In this second article of our short performance series, we want to look at the latter one of those problems.
25.04.2023
.NET
.NET 7 Performance: Introduction and Runtime Optimizations – Part 1

.NET 7 Performance: Introduction and Runtime Optimizations – Part 1

.NET 7 is fast. Superfast. All the teams at Microsoft working on .NET are keen to improve the performance and do so every year with each new .NET release. Though this time the achievements are really impressive. In this series of short articles, we want to explore some of the most significant performance updates in .NET and look at how that may affect our own projects. This first article is taking a deep look under the hood of the compiler and the runtime to look for some remarkably interesting and significant updates.
28.03.2023
.NET
Incremental Roslyn Source Generators: Using Additional Files – Part 7

Incremental Roslyn Source Generators: Using Additional Files – Part 7

In the previous article the Source Generator itself needed a 3rd-party library Newtonsoft.Json in order to generate new source code. The JSON-strings were hard-coded inside the Source Generator for simplicity reasons. In this article we will see how to process not just .NET code, but also other files, like JSON or XML.
21.03.2023
.NET
Understanding and Controlling the Blazor WebAssembly Startup Process

Understanding and Controlling the Blazor WebAssembly Startup Process

There are a lot of things going on in the background, when a Blazor WebAssembly application is being started. In some cases you might want to take a bit more control over that process. One example might be the wish to display a loading screen for applications that take some time for initial preparation, or when users are on a slow internet connection. However, in order to control something, we need to understand what is happening first. This article takes you down the rabbit hole of how a Blazor WASM application starts up.
07.03.2023