Platform Compatibility
ID |
csharp.platform_compatibility |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Reliability |
Language |
CSharp |
Tags |
platform, reliability |
Description
Reports calls to a small allow-listed set of Windows-only .NET APIs from code that does
not carry a [SupportedOSPlatform("windows")] attribute on the enclosing method or
type. Such calls compile cleanly on any platform but throw
PlatformNotSupportedException at runtime on Linux and macOS.
Rationale
EventLog, Microsoft.Win32.Registry, PerformanceCounter,
System.Drawing.Printing.PrinterSettings and a few others are Windows-only. The .NET 5+
analyser model uses [SupportedOSPlatform]/[UnsupportedOSPlatform] to mark this
explicitly. Code that ignores the marker silently shifts platform-specific behaviour
into production.
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.Versioning;
public class Logger
{
public void Write(string msg)
{
EventLog.WriteEntry("App", msg); // FLAW
}
public string Read()
{
return (string) Registry.GetValue("HKLM", "Name", ""); // FLAW
}
}
[SupportedOSPlatform("windows")]
public class WindowsLogger
{
public void Write(string msg)
{
EventLog.WriteEntry("App", msg); // OK
}
}
public class GuardedAtMethod
{
[SupportedOSPlatform("windows")]
public void Write(string msg)
{
EventLog.WriteEntry("App", msg); // OK
}
}
Remediation
Annotate the enclosing method or class with [SupportedOSPlatform("windows")], or
guard the call with OperatingSystem.IsWindows() and let the analyser flow-analyse it.
For genuinely cross-platform code, replace the Windows-only API with a portable
alternative (e.g. ILogger/Microsoft.Extensions.Logging instead of EventLog).