Add reference programmatically

Sanjay Kulkarni 0 Reputation points
2023-05-18T03:46:08.5733333+00:00

I have searched the net for almost 4 hours using a variety of phrases but could get a simple workable solution.
So here is my problem:
How to add references to a VB Project programmatically.

In VBA, I can use Application.VBE.ActiveVBProject.References.AddByFile ...
What is equivalent code in VB.Net

Developer technologies VB
{count} votes

1 answer

Sort by: Most helpful
  1. Castorix31 90,681 Reputation points
    2023-05-18T09:03:32.8766667+00:00

    It can be done with System.Reflection

    Test with Excel 2016 Interop (just open Excel, show 1 second, quit) :

        Dim sExcel = "Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
        Dim assembly = System.Reflection.Assembly.Load(sExcel)
        Dim oExcel = assembly.CreateInstance("Microsoft.Office.Interop.Excel.ApplicationClass")
    
        ' Test
        Dim methods As MethodInfo() = oExcel.[GetType]().GetMethods(BindingFlags.[Public] Or BindingFlags.Instance)
        Dim props As PropertyInfo() = oExcel.[GetType]().GetProperties()
        ' {Void set_Visible(Boolean)}
        ' {Void Quit()}
    
        InvokeMethod(oExcel, "set_Visible", True)
        Thread.Sleep(1000)
        InvokeMethod(oExcel, "Quit", Nothing)
        Marshal.ReleaseComObject(oExcel)
    
    

    with :

        ' https//sudonull.com/post/12432-Bug-when-working-TextBoxGetLineText-in-NET-WPF       
        Public Shared Function InvokeMethod(ByVal obj As Object, ByVal methodName As String, ParamArray methodParams As Object()) As Object
            Dim methodParamTypes = If(methodParams?.[Select](Function(p) p.GetType()).ToArray(), New Type() {})
            Dim bindingFlags = Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Static
            Dim method As MethodInfo = Nothing
            Dim type = obj.GetType()
            While method Is Nothing AndAlso type IsNot Nothing
                method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, Nothing)
                type = type.BaseType
            End While
            Return method?.Invoke(obj, methodParams)
        End Function
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.