title: How to programmatically update project references in a Visual Studio project
body: <p>I have a file structure like the following:</p>
  
  <pre><code>- binaries
     - binary1.dll
  - dev
     - &lt;developer-name&gt;
        - a.csproj
  -trunk
      - a.csproj
  </code></pre>
  
  <p>Developers who need to work on a.csproj will create a branch in dev and they will work from there. Our projects need to have a reference to binary1.dll in the binaries directory.</p>
  
  <p>If the reference is a relative path (the Visual Studio default) then the path will not work both for the project in trunk and the project in the developer's branch.</p>
  
  <p>To work around this problem I thought of creating an environment variable and using that in the project file instead:</p>
  
  <pre><code>&lt;Reference Include="binary1"&gt;
     &lt;HintPath&gt;$(MY_ENV_VAR)\binary1.dll&lt;/HintPath&gt;
  &lt;/Reference&gt;
  </code></pre>
  
  <p>This works perfectly, but I wanted to help developers add references more easily, so I wrote a program that will convert relative paths that point to binary1.dll (for example, from the dev branch a.csproj it would change the path <code>../../binaries/binary1.dll</code> to <code>$(MY_ENV_VAR)\binary1.dll</code>) but I have not figured out how to get that to work.</p>
  
  <p>If I use a pre-build event, the project is already loaded into memory and the event return an error because it cannot write the project file. </p>
  
  <p>Then I realized that I could override MSBuild targets, and attempted with the targets: <code>BeforeCompiler</code>, <code>AfterCompiler</code>, <code>BeforeBuild</code>, <code>AfterBuild</code> and in all of them the project is already locked. </p>
  
  <p>Then I ran into <a href="https://stackoverflow.com/questions/17726525/modify-csproj-in-pre-build-event">this answer</a> and I modified my code to call the executable in the <code>GenerateApplicationManifest</code> target, but that one doesn't seem to call the executable at all.</p>
  
  <p>Some other ideas that I have been playing with are creating a new project that does the updating of the second project and have a link between them, but that would duplicate the number of projects.</p>
  
  <p>I could also just change the depth of trunk, but that only hides the problem and doesn't really solve it. When developers create a branch inside their dev branch to work on different features or bugs then I have the same problem all over again.</p>
  
  <p>There might also be another feature which fixes this in a more elegant way, but I haven't been able to find anything.</p>
  
  <p>So my question: How do I get MS Build or pre-build events to modify a CS project?</p>