Reputation: 1
I'm using the "Microsoft.Windows.Compatibility" package to get the baseboard serial number in a .NET 6 application. My code looks like this:
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
var mobos = searcher.Get();
foreach (var m in mobos)
{
return m["SerialNumber"].ToString() ?? "";
}
When I run this code in a console application, it works correctly. However, when I create a DLL that executes this code and load that DLL dynamically with LoadContext, I get the following error:
System.Management currently is only supported for Windows desktop applications.
How can I fix this problem?
Verified Package Installation: Ensured that the "Microsoft.Windows.Compatibility" package is installed and referenced in both the console application and the DLL project. Target Framework: Confirmed that both the console application and the DLL project are targeting .NET
This is the DLL loader:
string dll_Path = Path.GetFullPath(dll_name);
var loadContext = new LoadContext(dll_Path);
var assembly = loadContext.LoadFromAssemblyPath(dll_Path);
Type type = assembly.GetType("MyClass");
MethodInfo method = type.GetMethod("MyMethod");
T function = (T)Delegate.CreateDelegate(typeof(T), method);
function.DynamicInvoke(inputs);
Upvotes: 0
Views: 753
Reputation: 20086
If you want to use new .NET (not the old .NET Framework), you will have to ditch Microsoft.Windows.Compatibility
and all that DLL dynamic loading rigmarole. Use the System.Management
package from Nuget, and set your application target framework to net8.0-windows
to indicate that it is Windows-only. The following example prints my laptop baseboard serial number:
<!-- test.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configurations>Debug;Release</Configurations>
<ImplicitUsings>enable</ImplicitUsings>
<TargetFramework>net8.0-windows</TargetFramework>
<OutputType>exe</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Management" Version="8.0.0" />
</ItemGroup>
</Project>
// test.cs
static class Program
{
static void Main ()
{
try
{
var searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
var mobos = searcher.Get();
foreach (var m in mobos)
Console.WriteLine (m["SerialNumber"].ToString() ?? "") ;
}
catch (Exception e)
{
Console.WriteLine (e) ;
}
}
}
Upvotes: 1
Reputation: 96
Apparently this is due to using .Net Core...
I found this: How to use it
This is what worked:
in the csproj file. Add the following usually at the beginning:
<PropertyGroup>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
Reload project
Upvotes: 0