Why is this an issue?
The parameter to Assembly.Load includes the full specification of the dll to be loaded. Use another method, and you might end up with
a dll other than the one you expected.
This rule raises an issue when Assembly.LoadFrom, Assembly.LoadFile, or Assembly.LoadWithPartialName is
called.
Exceptions
The rule does not raise an issue when the methods are used within an AssemblyResolve event handler. In this context,
using Assembly.Load can cause a StackOverflowException due to recursive event firing, making Assembly.LoadFrom
or Assembly.LoadFile the appropriate choices.
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
}
static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
return Assembly.LoadFrom("MyAssembly.dll"); // Compliant: within AssemblyResolve handler
}
How to fix it
Code examples
Noncompliant code example
static void Main(string[] args)
{
Assembly.LoadFrom("MyAssembly.dll"); // Noncompliant
}
static void Main(string[] args)
{
Assembly.LoadFile(@"C:\MyPath\MyAssembly.dll"); // Noncompliant
}
static void Main(string[] args)
{
Assembly.LoadWithPartialName("MyAssembly"); // Noncompliant
}
Compliant solution
static void Main(string[] args)
{
Assembly.Load("MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); // Compliant
}
static void Main(string[] args)
{
Assembly.Load("MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); // Compliant
}
static void Main(string[] args)
{
Assembly.Load("MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); // Compliant
}
Resources
Documentation
- Microsoft Learn - Assembly.Load Method
- Microsoft Learn - Assembly.LoadFrom Method
- Microsoft Learn - Assembly.LoadFile Method
- Microsoft Learn - AppDomain.AssemblyResolve Event
- Microsoft Learn - Assembly.LoadWithPartialName Method
- Microsoft Learn - Resolve assembly loads - What the event handler should not do