Unable to access classes in my .dll in C#

86 views Asked by At

I created Library with some public fields:

namespace ClassLibrary1
{
    public class Class1
    {
        public int i = 10;
        public void PrintName()
        {
            Console.WriteLine("Hello");
        }
    }
}

built it and created dll file - ClassLibrary1 with Class1. Then I moved the dll to the debug folder in my project and in references I added this dll as well. I created object of the class Assembly at it finds the library. But as soon as I try to get type of the items in the library, it turns out that the existing public Class1 in my library doesn't exists.

using System;
using System.Reflection;

namespace First_dll_just_connectLib_96
{
    internal class Program
    {
        const string ASSEMBLEY = "ClassLibrary1";

        static void Main(string[] args)
        {
            Assembly as1;

            as1 = Assembly.Load(ASSEMBLEY);  // This doesn't throw any exceptions
            Console.WriteLine($"{ASSEMBLEY} exists");

            Type[] types;
            try
            {
                types = as1.GetTypes();  // This throws an exception. See output below
            }
            catch (ReflectionTypeLoadException e)
            {
                var typeLoadException = e as ReflectionTypeLoadException;
                var loaderExceptions = typeLoadException.LoaderExceptions;

                foreach (Exception ex in loaderExceptions)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.ReadLine();
                return;
            }

            // This never runs
            foreach (Type t in types)
            {
                Console.WriteLine(t.Name);
            }
            Console.ReadLine();
        }
    }
}

The output of the program:

ClassLibrary1 exists
Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I expected it to print the name of my class, Class1. I tried moving the .dll to different folders to no avail. I think the program actually loads the library, but for some reason I can't access my classes inside it.

0

There are 0 answers