Migrating from .NET Framework WinForms

A WinForms application written for .NET Framework 4.8 is not a different application from one written for .NET 10. The form, the controls, the events and the designer files are the same API. What changes is the project around them, the startup boilerplate, the place the settings live and a handful of platform defaults. This lesson migrates one, and the compiler is the judge of what still works.

The project file

The old project lists every file and every reference by hand, and the framework version is a separate element. This is the shape Visual Studio wrote for a WinForms application for years:

<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <OutputType>WinExe</OutputType> <TargetFrameworkVersion>v4.8</TargetFrameworkVersion> <UseWindowsForms>true</UseWindowsForms> </PropertyGroup> <ItemGroup> <Reference Include="System.Windows.Forms" /> <Reference Include="System.Drawing" /> </ItemGroup> <ItemGroup> <Compile Include="Program.cs" /> <Compile Include="Form1.cs"><SubType>Form</SubType></Compile> <Compile Include="Form1.Designer.cs"><DependentUpon>Form1.cs</DependentUpon></Compile> <EmbeddedResource Include="Form1.resx"><DependentUpon>Form1.cs</DependentUpon></EmbeddedResource> </ItemGroup> </Project>

The SDK project replaces all of it with the one file of lesson 002. The glob takes every *.cs and every *.resx, so the Compile and EmbeddedResource items disappear. The references to the framework assemblies disappear because the framework is named by TargetFramework. TargetFrameworkVersion v4.8 becomes net10.0-windows, and UseWindowsForms stays, now as the switch that brings the desktop framework and the analyzers.

Two more files have no place in the new project. packages.config was the list of NuGet packages for the old project format; it becomes PackageReference items in the project file, and the packages folder goes away. Properties/AssemblyInfo.cs held the version and the title as attributes; those move to properties in the project file, and the SDK generates the file. A custom attribute that is not one of the standard ones can stay in a source file.

The old Main still compiles

The first surprise of a migration is how little of the code has to change. This is the startup code of a .NET Framework form, unchanged, built for net10.0-windows:

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } internal sealed class Form1 : Form { public Form1() { Text = "Old style"; ClientSize = new Size(340, 120); Controls.Add(new Label { Text = "Written for .NET Framework 4.8", AutoSize = true, Location = new Point(16, 16), }); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. Both startup calls still exist and still do what they did: EnableVisualStyles turns on the themed controls, and SetCompatibleTextRenderingDefault(false) chooses GDI text rendering for the controls created afterwards. What is missing is everything .NET 6 added around them, and that is the second half of the migration:

app.config and user.config

A .NET Framework application kept its settings in an App.config that became app.exe.config: the appSettings section for the application's own values, and the userSettings section that Properties.Settings wrote to a per-user file under %LOCALAPPDATA%. .NET 10 still reads an app.config through ConfigurationManager for compatibility, and a new application should not: JSON through System.Text.Json is the format the rest of the course uses.

Migrating is a read of the two XML sections and a write of one JSON object. The program below does exactly that with XDocument, and it was built and run here:

using System; using System.Collections.Generic; using System.Text.Json; using System.Xml.Linq; Console.WriteLine("a legacy app.config and user.config, read and merged"); var appConfig = """ <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="Server" value="db01" /> <add key="Timeout" value="30" /> </appSettings> </configuration> """; var userConfig = """ <?xml version="1.0" encoding="utf-8"?> <configuration> <userSettings> <Notes.Properties.Settings> <setting name="RecentFile" serializeAs="String"> <value>C:\notes\todo.txt</value> </setting> <setting name="WindowWidth" serializeAs="String"> <value>1024</value> </setting> </Notes.Properties.Settings> </userSettings> </configuration> """; var settings = new SortedDictionary<string, string>(); var app = XDocument.Parse(appConfig); foreach (var add in app.Descendants("appSettings").Elements("add")) { settings[(string)add.Attribute("key")!] = (string)add.Attribute("value")!; } var user = XDocument.Parse(userConfig); foreach (var setting in user.Descendants("setting")) { settings[(string)setting.Attribute("name")!] = (string)setting.Element("value")!; } foreach (var pair in settings) { Console.WriteLine($"{pair.Key} = {pair.Value}"); } Console.WriteLine(JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true }));

dotnet run

a legacy app.config and user.config, read and merged
RecentFile = C:\notes\todo.txt
Server = db01
Timeout = 30
WindowWidth = 1024
{
  "RecentFile": "C:\\notes\\todo.txt",
  "Server": "db01",
  "Timeout": "30",
  "WindowWidth": "1024"
}

The output is the real run. The two sections merged into one object, the JSON writer escaped the backslashes of the Windows path, and every value came out as a string because the dictionary is a dictionary of strings. That is the honest shape of an old settings file: nothing in it is typed. The modern application reads the same data into a record with string and int members, and the deserialiser does the conversion, which is the next listing.

Two differences matter for a real migration. The old appSettings was global and the old userSettings was per user; a JSON file can be either, and the folder decides. And the old file was found by the runtime next to the exe, while a JSON file needs a path that works in a normal folder, a single-file bundle and a ClickOnce cache, which is why the modern code below uses AppContext.BaseDirectory.

The modern Main

The same application after the migration: the generated Initialize, a settings record loaded from JSON, and a form that takes the settings instead of reading a static. Built and not run:

using System; using System.Drawing; using System.IO; using System.Text.Json; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); var settings = SettingsStore.Load("appsettings.json"); Application.Run(new Form1(settings)); } } internal sealed record Settings(string UserName, int WindowWidth); internal static class SettingsStore { public static Settings Load(string path) { if (!File.Exists(path)) { return new Settings(string.Empty, 800); } var json = File.ReadAllText(path); return JsonSerializer.Deserialize<Settings>(json) ?? new Settings(string.Empty, 800); } public static void Save(string path, Settings settings) => File.WriteAllText(path, JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true })); } internal sealed class Form1 : Form { public Form1(Settings settings) { Text = string.IsNullOrEmpty(settings.UserName) ? "Notes" : $"Notes - {settings.UserName}"; ClientSize = new Size(settings.WindowWidth, 240); Controls.Add(new TextBox { Dock = DockStyle.Fill, Multiline = true }); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The file path is still relative here, which resolves against the working directory and is wrong for a deployed application; the version on the next line is the one to use: Path.Combine(AppContext.BaseDirectory, "appsettings.json"). The record gives the two settings a type, and a missing file gives the defaults instead of an exception, which is the behaviour Properties.Settings had.

The refactor from Properties.Settings.Default.WindowWidth to a settings parameter is the migration's real work. A static settings class is a global that every form reads, so the form cannot be constructed with a different value in a test; a record passed to the constructor is the same data with the seam that lesson 057 described. The generated Settings.Designer.cs of the old project can be deleted once no code reads it.

The designer files

Form1.cs, Form1.Designer.cs and Form1.resx migrate as they are. The designer of .NET 10 is the out-of-process one in Visual Studio, and it opens the same partial class; InitializeComponent keeps its shape. Four small differences appear in a form that was generated years ago:

A form that used this.EnableVisualStyles() or an app.manifest for DPI loses both jobs to the project file. A form that drew with GDI+ keeps its code: System.Drawing.Common is Windows-only in .NET 10, which is fine for a WinForms application and a breaking change for a library that was shared with ASP.NET Core.

A migration checklist

  1. Create the SDK project beside the old one and copy the source folders; do not edit the old project into the new format by hand.
  2. Set TargetFramework to net10.0-windows, UseWindowsForms and EnableWindowsTargeting when the build machine is not Windows.
  3. Replace packages.config with PackageReference items, one at a time, and build after each.
  4. Delete Properties/AssemblyInfo.cs and move the version to the project file.
  5. Run the build and read the warnings: obsolete APIs, nullable warnings and the analyzers are the migration's real list of work.
  6. Replace app.config and Properties.Settings with a typed settings record and a JSON file, keeping the old file for one release as the import source.
  7. Check the layout after the font change, and set ApplicationDefaultFont if the old sizes must be kept.
  8. Move the DPI setting from the manifest to ApplicationHighDpiMode, and test on a scaled monitor.
  9. Publish and deploy with lesson 066 or 067, and keep the .NET Framework build until the new one has run in production.

Exercises

  1. Add a Culture setting to the JSON record and use it to set CurrentUICulture in Main.
  2. Change the settings program to read the file path from AppContext.BaseDirectory and explain why that is the right base.
  3. List three warnings you would expect from a large .NET Framework form and say which one you would fix first.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What replaces TargetFrameworkVersion v4.8?

    Answer

    TargetFramework net10.0-windows

    The framework is named once, and the references follow.

  2. What happens to the Compile items of an old project?

    Answer

    The SDK globs every .cs file, so they are not listed

    The default items include all C# files.

  3. What replaces packages.config?

    Answer

    PackageReference items in the project file

    The old package list format is not used by SDK projects.

  4. Which old startup call is still valid in .NET 10?

    Answer

    Application.EnableVisualStyles

    The legacy listing built with both calls unchanged.

  5. Where does the high-DPI mode live in a modern project?

    Answer

    ApplicationHighDpiMode in the project file

    ApplicationConfiguration.Initialize applies it before the first window.

  6. Why can an old form resize when opened in the new designer?

    Answer

    The default font changed from Microsoft Sans Serif to Segoe UI

    AutoScaleDimensions is computed for the old font.

  7. What did the merge program print for the recent file?

    Answer

    RecentFile = C:\notes\todo.txt, and the JSON escaped the backslashes

    The JSON writer doubles the backslash.

  8. Why is every JSON value a string in the merge program?

    Answer

    The dictionary is a dictionary of strings

    A typed record is what converts them, in the modern listing.

  9. Which path base should a deployed application use for its settings file?

    Answer

    AppContext.BaseDirectory

    It is right in a folder, a single-file bundle and a ClickOnce cache.

  10. What is the migration's real code work?

    Answer

    Replacing static settings and reading the build warnings

    The API is the same; the globals and the warnings are the work.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev