4

I am creating Class Files programmatically for UnitTests with NUnit. I could already add them to TFS Source Control. What I now need, is that I want to add them programmatically to the Project.

I have found several approaches, but I got none working... I don't want to edit the XMl-File manually.

Do you have some code snippets?

1
  • Are you generating unittests on the fly ? or do you just need a project file which contains all class files that reside in a directory (structure) because they used to be compiled differently ? Commented Dec 11, 2012 at 23:00

1 Answer 1

6

The naïve solution would be to edit the XML file manually. However, you don't have to do this.

You can use the Microsoft.Build.Evaluation.Project object model to manipulate Visual Studio project files. See this answer for more information on the differences between the Microsoft.Build.Evaluation and Microsoft.Build.Construction namespaces.

The following example opens YourProject.csproj and adds a new file called YourFile.cs as a Compile item type, then saves the project file back to disk.

using Microsoft.Build.Evaluation;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var project = new Project(@"YourProject.csproj");
            project.AddItem("Compile", "YourFile.cs");
            project.Save();
        }
    }
}
2
  • Only for .net 4.0 and above ?
    – Kiquenet
    Commented Feb 6, 2014 at 13:57
  • I was about to edit the XML manually. That would've been a nightmare. This is what I'm looking for.
    – MC10
    Commented Jul 17, 2015 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.