Microsoft Visual Studio structures work as ‘Solutions’, each of which can contain multiple ‘Projects’. I create each project in it’s own sub-directory. This leads to a problem…
I wanted to add a project to my solution that used some C# files from another project in the same solution. I tried the straightforward way, choosing ‘Add files…’ on the target project and navigating to the files in the source project. This created a new copy of the file in the target directory – not what I wanted. If I later made changes to the file in one project, I’d have to manually go and make the changes to the same file in the other project, or allow them to diverge. A maintenance headache.
So I did a hack:
- Add the files from the source project to the target project as above
- Save the target project
- Open the target project file (e.g. ‘.csproj’) in a text editor
- Find the file refererences – something like
<Compile Include="FileFromSourceProject.cs" /> - Change to
<Compile Include="..\SourceProject\FileFromSourceProject.cs" /> - Save the project in the text editor
- Delete the unneeded new file copies in the target project directory
- Reopen the target project in Visual Studio. (This happened automatically.)
OK! Now the files show up in the Solution Explorer with a little ‘reference’ icon.
Anyone know how to do this without hacking?
Anyway, this works. Just one file in the file system, logically shared by two projects.
To make this useful in practice, I started using conditional compilation symbols (in project properties -> build) and #if … #endif sections in my code. It’s clumsy and C-ish, but it got the job done.
One more note here: The file will use the compilation symbols from whatever project you open it from – so if you’ve disabled some code for one project, it won’t show up in intellisense, etc. This sometimes means you’ll want to close the file and re-open it by clicking on the right icon or reference in the Solution Explorer to get the right symbols.
It’s simple, but enough of a hack that I had to think a bit to remember how to do it the second time. Maybe this post will help.