How to add references by automation

It's easy but I always forget the steps. I have to look in my code in order to remember. So here the steps:

1. Add a reference to VSLangProj. If you are writing a macro you don't need this step.
2. Add the using clause (C#)
            using VSLangProj; 

 3.    And use this function

  public bool AddReference(EnvDTE.Project project, string reference)
  {
      VSProject proj = m_Project.Object as VSProject;
      System.Diagnostics.Debug.Assert(proj != null); // This project is not a VSProject
      if (proj == null)
          return false;
      try
      {
          proj.References.Add(reference);
      }
      catch (Exception ex)
      {
          string message = String.Format("Could not add {0}. \n Exception: {1}", reference, ex.Message);
          System.Diagnostics.Trace.WriteLine(message);
          return false;
      }

      return true;
  }

In order to add a reference to a project you have to use proj.References.AddProject insted proj.References.Add.

If you wanna add a reference to an assembly that is in the GAC then pass just the dll name insted of the full path.


 

4 Comments

  • hi,
    I want to add references in a VS 2008 project through code. I've included VSLangProj and ENVDTE. But not finding any options.
    Any help...


  • I want to be able to add a reference even if the referenced assembly I'm adding cannot be resolved. I know this may seem unusual, however for my purposes it fits my needs.

    My problem really boils down to, I'd be able to construct a project correctly despite assemblies being missing. Those should be able to be added later (imo).

  • Hi,

    I'm using automation to configure references between a set of automatically created projects.
    But when I execute the code above nothing happens: no error, no exception and no reference is added.
    I've checked that the 'References' property really contains the added references but when I open the project under VS, no reference has been added.

    Any idea about the source of the problem?
    Many thanks.

Comments have been disabled for this content.