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:
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. 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.
I have resolved it with following changes in code and configurations in project properties.
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);
Add following properties for project:
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<PlatformTarget>x86</PlatformTarget>
Then publish the app with command:
dotnet publish -a x86 --sc true