Search code examples
.netwindows.net-6.032bit-64bitdotnet-publish

.NET 6.0 x86 app doesn't set registry key successful


We want to set the OnlyUseLatestCLR registry key with a .NET 6.0 app. This app will run on both x86 and x64 machines and the machines won't have .NET 6 installed. So we publish this app as single file and with x86 arch use this command:

dotnet publish -a x86 --sc true

And following code that we are using to set the OnlyUseLatestCLR value:

RegistryKey clrKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework", true);
clrKey.SetValue("OnlyUseLatestCLR", 0);

But above code doesn't set the OnlyUseLatestCLR value to 0. There is no exception thrown.

What we tried:

  1. Debug the application in Visual Studio, it can set the key successully.
  2. Publish it with x64 arch, it can set OnlyUseLatestCLR successful on x64 machine. But the application cannot be launch on x86 machine.
  3. Use batch file with command REG ADD "HKLM\Software\Microsoft\.NETFramework" /t REG_DWORD /v OnlyUseLatestCLR /d 0 /f to set the value. If we call the batch file manually, it can set successful, but if we call it from .NET 6.0 app with publishing as x86 single file, set failed without exception.
  4. Try import the key with .reg file. If we import the .reg manually, it can successful. But if we try import with .NET 6.0 app programmatically and publishing as x86 single file, it failed without any exception again.
    Process proc = new Process();
    proc.StartInfo.FileName = "regedit.exe";
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.UseShellExecute = false;
    string command = "/s regeidfile.reg";
    proc.Start();
    proc.WaitForExit();

Expected: We want the .NET 6 app can be published with single file and set the OnlyLatestCLR successfully.


Solution

  • I have resolved it with following changes in code and configurations in project properties.

    1. When opening the registry key, assign the registry view with following code:

      RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
      RegistryKey frameworkKey = baseKey.OpenSubKey(@"Software\Microsoft\.NETFramework", true);
      
    2. Add following properties for project:

      <RuntimeIdentifier>win-x86</RuntimeIdentifier>
      <PlatformTarget>x86</PlatformTarget>
      
    3. Then publish the app with command:

      dotnet publish -a x86 --sc true