mirkojpn
mirkojpn

Reputation: 13

How to dynamically load an Assembly Into My C# program, .NET Framework 4.7

I'm building an Excel to .bin console app using NPOI, what I'm looking to do is compare read data to to the class one, let me explain better...

If I have an Excel file : Sample.xlxs

_valueOne _valueTwo
0.0f testString

Then with my app I'll convert it into a Datatable (then serialize it) but I'll check for any error on the Excel file before I'll write the Datatable, for example in the final class that will be:

public class Sample
{
   public float _valueOne;
   public string _valueTwo;
}

I want to load this class to compare the value got from the Excel file to find some error (like is a string instead a float)

Final classes are contained in another project, so I would like to know if there is a way to "import" it.

Actually I'm using

        private static System.Type GetType(
        string in_assemblyPath,
        string in_className)
    {
        System.Type typeCur
            = System.Type.GetType(in_className);
        if (typeCur != null)
        {
            return typeCur;
        }
        else
        {
            Debug.WriteLine(in_assemblyPath + "/" + in_className + ".cs");
            try
            {

                System.Reflection.Assembly asm
                            = Assembly.LoadFrom(in_assemblyPath + "/" + in_className + ".cs");
                typeCur
                    = asm.GetType(in_className);
                if (typeCur != null)
                {
                    return typeCur;
                }

            }catch(Exception ex )
            {
                Debug.WriteLine(">>>>>>>>>>>   " + "Error On Assembly Load"+" <<<<<<<<<" );
                Debug.WriteLine(ex.StackTrace);
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(">>>>>>>>>>>   " + "End Error Report" + " <<<<<<<<<");
            }

        }

        return null;
    }

but I got an error message that say : The module was expected to contain an assembly manifest.

Upvotes: 0

Views: 476

Answers (1)

Emanuele
Emanuele

Reputation: 888

If you are using visual studio: you need to go to your project, go to reference > Right Click > Add reference. In the window that appears select Project, and then select the project that contains classes. Then save.

EDIT: if you want to add it in a dynamic way, then, as @Romka suggested use something like this:

     var MainAssembly = Assembly.Load("yourpathtodll.dll");
     Type t = MainAssembly.GetType("Yournamespace." + filename);
     var finalobj = Activator.CreateInstance(t);

Then you can use reflection the get fields and properties.

Upvotes: 1

Related Questions