JadedEric
JadedEric

Reputation: 2083

File not found error when reflecting assembly types

Iterating through a directory for *.dll files, find them and create an Assembly reference for each file.

Once I have a reflected object, I iterate through all the types available in each, from which I'd like to get the custom attributes for each type in the collection:

string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "Methods", "*.dll");

foreach (string s in files)
{
    Assembly asm = Assembly.LoadFile(s);

    Type[] asmTypes = asm.GetTypes();

    bool isCorrect = false;

    foreach (Type type in asmTypes)
    {
        1. var customAttribs = type.GetCustomAttributes(typeof(BaseModelAttribute), false);
    }
}

[Update] : exception raised at line # 1

This code works all the way up to the foreach...loop when I get an exception saying that the file could not be found, which is weird as I created an Assembly reference from the file higher up in the code block (not mentioned in code).

[Update]: Erno was correct in in assuming a reference could not be established. Base, for some reason needs to be defined outside of the reference pool (being in the bin directory) even though it's not actually needed by the application. Does not makes sense to me, but it works. Thanks.

Upvotes: 2

Views: 1119

Answers (2)

If anyone is reading this in 2024, I had the same error and, looking for more information, I saw that it was only necessary to use Assembly.LoadFrom(filePath) instead of Assembly.LoadFile(filePath). This way, the assembly is loaded and can resolve its dependencies.

Upvotes: 0

Emond
Emond

Reputation: 50682

When .NET is not able to find a file it probably is trying to load an assembly that the currently reflected assembly is dependent on.

You can use Fuslogvw.exe (SDK) to find out what assembly is being searched for.

Upvotes: 2

Related Questions