Wednesday, June 3, 2009

Reusing Source Files in Multiple Visual Studio Projects

Sometimes you have a file F in a project P1, and you want to add it to your project P2 without actually getting a copy of the file. In Visual C++ you simple choose Add Existing Item, the rest is taken care of for you. However, in Visual C# (and maybe Visual Basic which I didn't test) even if you choose Add Existing Item and pick a file from an external folder, the file will be copied to your project folder.

I really find it awkward especially in case you have your files under version control. Luckily, I've just found a simple solution how you can share your source code between two or more projects without copying the files. At least for C# it works just perfectly. Furthermore, no 3rd party software is required!

You still choose Add Existing Item, then in the File Open dialog box you select your file and press the small arrow on the Add button. You should choose the Add As Link menu item:

Adding a file as a reference in Visual Studio

Then the your file reference should be displayed as an icon with a shortcut arrow in the solution tree:

File reference displayed in Visual Studio solution tree

Cheers,
Kirill