4

How do you programmatically find & iterate all project & dll references within a Visual Studio 2010 solution?

I can iterate all projects and found the Project.ProjectItems property and Project.Properties but have not found any way to reference the references (pun intended).

This is happening in an add-in, so a DTE solution is preferable to anyone suggesting we iterate the files.

Proposed solution based on the answers below:

You need to find and include a reference to VSLangProj.dll (e.g. in Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies)

Then you can iterate all selected project's project & DLL references like this:

foreach (Project project in (object[])_applicationObject.ActiveSolutionProjects)
{
    VSProject vsProject = project.Object as VSProject;
    if (vsProject != null)
    {
        foreach (Reference reference in vsProject.References)
        {
              // Do cool stuff here
        }
    }
}

Info for Tomas Lycken:

_applicationObject is a private member in my add-in, e.g.

private DTE2 _applicationObject;

I set it in the connection like this:

public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
Community
  • 1
  • 1
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • I'm trying to recreate this. How do I instantiate `_applicationObject`, and what type is it? – Tomas Aschan Aug 12 '11 at 08:12
  • Thanks! I was trying to do a simplified version of this in a plain macro. It turned out that the static property `DTE.ActiveSolutionProjects` got me where I wanted, so I had no need of instantiating an `_applicationObject`. Wouldn't have found it without the DTE hint. Great thanks! – Tomas Aschan Aug 12 '11 at 10:49

2 Answers2

3

C# and VB projects have an 'Object' property which you can cast into a VSProject, from which you can access the references. There's sample VB code on those pages.

stuartd
  • 70,509
  • 14
  • 132
  • 163
3

You can access the VB/C# specific VSProject object from the Object property of the Project object. VSProject has a References property, through which you can drill down to the individual references.

It has to be this way, if you think about it, since not all projects loaded in visual studio will necessarily support references to .NET assemblies, so it has to be something specialized for C#/VB (and other .NET languages), rather than off of the core Project object.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448