title: How to programmatically include a file in my project?
body: <h2>Background</h2>
  
  <p>I'm making a helper application that reformats some code files and creates new code files, which are to be added to my other project, so I could use the new code right away, but I'm having serious trouble adding that new code file into my project automatically. By the way it's in c# and the helper app is WinForms.</p>
  
  <h2>Failed attempts</h2>
  
  <p><a href="https://stackoverflow.com/questions/15180527/include-in-project-programmatically">This question</a>'s only answer has two ways of doing that, but I couldn't make any of them work. With the first I can't find a <code>Microsoft.Build</code> assembly to reference, and in the other there are clearly not enough arguments for a command line.</p>
  
  <h2>Question</h2>
  
  <p>How do I programmatically include a file into a project without the use of third-party applications?</p>
  
  <p>Basically, I'm looking for the equivalent of this:</p>
  
  <p><img src="https://i.stack.imgur.com/ri4E4.png" alt=""></p>
  
  <p>...But done using code.</p>
  
  <h2>Requirements</h2>
  
  <p>These are the features I suppose the solution should offer: </p>
  
  <ul>
  <li>Select the <em>solution</em> which has the <em>project</em> we're adding the file to</li>
  <li>Select <em>project</em> into which the file is to be added</li>
  <li>Select <em>directory</em> within the project</li>
  <li>And, of course, the <em>file</em> which we're adding</li>
  </ul>
  
  <h2>Progress</h2>
  
  <p>With user @psubsee2003's help I was able to find the <code>Microsoft.Build.dll</code> file in <code>C:\Windows\Microsoft.NET\Framework\v4.0.30319</code> folder on my computer and successfully import it by changing my project's target framework to version 4 <em>Full profile</em>, not the default Client profile.</p>
  
  <p>And I found how to use the <code>AddItem</code> method:</p>
  
  <pre><code>var p = new Microsoft.Build.Evaluation.Project(@"C:\projects\MyProject.csproj");
  p.AddItem("Compile", @"C:\folder\file.cs");
  p.Save();
  </code></pre>
  
  <p>The file will appear in project's root folder unless the project already had a folder called <code>folder</code>, in which case the file will be placed there. So basically the file will be placed in the deepest folder chain found in the original file's path going towards the root folder.</p>