How To Get AssemblyName of the application

I am trying to load a form dynamically at runtime.  I want to get a handle to the Form just from the form's name.  So far it seems like CreateInstanceWithUnwrap should do what I want.  Unfortunately I'm not sure how to get the AssemblyName of the Application itself.  Its a simple Windows Form app.  Here is the code I'm using:

AppDomain currentDomain = AppDomain.CurrentDomain;
object instance = currentDomain.CreateInstanceAndUnwrap( "", "Form2" );

I was assuming that if you didn't pass in the first parameter that the current Assembly would be assumed.  Unfortunately I get the error: String cannot have zero length.

Is there an easier way to do this   Or how do I get the Assembly Name for the application itself.  I looked in AssemblyInfo.cs but didn't see anything promising there...

Any ideas

Thanks,
David House


Answer this question

How To Get AssemblyName of the application

  • Minh Tan Duong

    Thanks for all the tips.  All the information really helps.. :)
  • swart

    Or, if you know exactly which form you want to deal with simply use typeof (or GetType in Visual Basic)

    Form2 frm = (Form2)Activator.CreateInstance(typeof(Form2));

  • DARK_IBO

    I think you can do this with less code:

    Assembly a = Assembly.GetExecutingAssembly();
    Type formType = a.GetType("WindowsApplication6.Form2");
    Form f = (Form)Activator.CreateInstance(formType);
    f.Show();

    This is more efficient than using an object handle API like CreateInstanceAndUnwrap.  This API is designed to be used when you need to communicate across an app domain boundary.

  • JudahR

    You need to use either Assembly.GetExecutingAssembly() or Assembly.GetEntryAssembly(), depending on what you need.

    I did the following and it worked.

    First add your using statements:

    <b>using System.Reflection;</b>

    Then in a Button's click event:

    <b>Form1 frm = (Form1)AppDomain.CurrentDomain.CreateInstanceAndUnwrap                                                                     (Assembly.GetEntryAssembly().FullName, typeof(Form1).ToString());
    frm.ShowDialog();</b>

    Good luck
     - mike

  • Kim Schjefstad

    Thank you very much!  That got me in the right direction.  Here is the code I ended up with:

    Form f2 = (Form)AppDomain.CurrentDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName,"WindowsApplication6.Form2" );
    f2.Show();

    This way I don't have to have prior knowledge of the Form before loading and showing it.  The Assembly.GetExecutingAssembly().FullName was the piece that I was missing.  And also it has to be "WindowsApplication6.Form2", not just "Form2".  I figured that out by looking at the result of typeof(Form1).ToString().

    Thanks for all the help!
    David

  • How To Get AssemblyName of the application