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:
- Debug the application in Visual Studio, it can set the key successully.
- Publish it with x64 arch, it can set OnlyUseLatestCLR successful on x64 machine. But the application cannot be launch on x86 machine.
- 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. - 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.