I am trying to load a c# DLL assembly at runtime and find the attributes and their contained values from class methods using reflection.
As of right now I have code that looks like this to load the assembly and look for the attributes:
private void ReadAttributes()
{
Assembly assembly = Assembly.LoadFile(Path.GetFullPath("TestLib.dll"));
Type type = assembly.GetType("TestLib.test");
if (type != null)
{
MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (MethodInfo m in methods)
{
foreach (Attribute a in Attribute.GetCustomAttributes(m, false))
{
Console.WriteLine(a);
foreach (FieldInfo f in a.GetType().GetFields())
{
Console.WriteLine("\t{0}: {1}", f.Name, f.GetValue(a));
}
}
}
}
}
and the code that is in the dll file looks like this:
[AttributeUsage(AttributeTargets.Method)]
public class Author : Attribute
{
public string name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0;
}
}
public class Test
{
private string name = "";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
[Author("Andrew")]
public void Message(string mess)
{
Console.WriteLine(mess);
}
[Author("Andrew")]
public void End()
{
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
public double Power(double num, int pow)
{
return Math.Pow(num, pow);
}
}
If I use this code in the same assembly rather than dynamically loading it, it works. But when I dynamically load the assembly like this the methods get loaded but no attributes.
Is there something incorrect with my code or is what I'm trying to do just not possible with System.Reflection?
Note: The dll is not a dependency of the main program so we can't reference the attribute/class type during compilation.