Thursday, April 24, 2008

Sharing files between VS projects

One of the interesting features available in Visual Studio managed projects (VS2005 and VS2008) that I keep forgetting about is the ability to add same file to several projects as "link" rather as physical copy. To add existing file to the project as a link you just need to select "Add->Existing Item" and then use well-hidden "Add As Link" add option in the dialog:

The file added as link then will have special icon in solution explorer. And if the file linked is under source control, it will not be added to repository again; the icon will show the status of original file.

What is this feature good for? Several examples:

  1. You have class library project where some class have internal methods, and you want to use those methods (for example, for testing). Then you can create additional project and link the files from the class library into it – and voila! you can use internal logic and do that in separate project
  2. Share certain file between several projects. You might wonder what file is a good candidate for that kind of sharing; well, how about AssemblyInfo.cs file? That way you can easily make sure that all related assemblies have the same version
  3. One interesting usage scenario was mentioned on MSDN forums: it is not a secret that when you build managed project it generates lots of junk in the project folder (obj and bin folders come to mind). While you can redirect output, it turns out getting rid of this obj folder is quite involved. But suppose you stored your source files elsewhere and would just link them into the project being built? That way you can make maintain clear separation between source code and build plumbing (which is the main purpose of C#/VB project)

I am not advocating the wide usage of the links instead of good ol' files; but that's a neat alternative to be aware of.


Fredrik said...

Another usage is for strong name key files; we use this approach to sign multiple projects with the same key.

Mark said...

I'm trying to get this to work with master pages being shared across multiple projects. The problem I run into is that I lose designer support in all of the projects that use the linked master page files. Does anyone have any ideas how to get this to work?

eugenez said...


Sorry to say that I do not have any idea about web projects (are you using web site project). Am not sure that it is supported - anyhow I would file the issue on Microsoft Connect