How to Create/Generate Project File Programmatically in .Net?

There are situations where the source files are generated dynamically either through templates or codeDOM, therefore we need a mechanism to package those source files in a project. .Net allows to generate project files dynamically using the Microsoft.Build.Construction.

Generating Project File Dynamically

In this post lets see with an example how we can generate csproj file, add the source files and references dynamically into the csproj file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Microsoft.Build.Construction;

namespace OnTheFlyCompilation
{
    class Program
    {
        static void Main(string[] args)
        {
            var root = ProjectRootElement.Create();
            var group = root.AddPropertyGroup();
            group.AddProperty("Configuration", "Release");
            group.AddProperty("Platform", "x64");

            // references
            AddItems(root, "Reference", "System", "System.Generic");

            // items to compile
            AddItems(root, "Compile", @"..\..\SampleSource.cs");

            var target = root.AddTarget("Build");
            var task = target.AddTask("Csc");
            task.SetParameter("Sources", "@(Compile)");
            task.SetParameter("OutputAssembly", "SampleSource.dll");

            root.Save("SampleSource.csproj");
        }

        private static void AddItems(ProjectRootElement elem, string groupName, params string[] items)
        {
            var group = elem.AddItemGroup();
            foreach (var item in items)
            {
                group.AddItem(groupName, item);
            }
        }
    }
}

To create a csproj file as shown in the code above we need to create ProjectRootElement. Once root is created we need to create different sections of the project file and set the necessary properties. Reference and Compile are such sections wherein we need to add the assemblies and source files respectively which are needed in the project.

At the end we need to save the project giving it a suitable name. 

Sample Screenshots

Dynamically created project file

New .Net project file

Above two figures shows the dynamically generated project file and the same opened in Visual Studio. 

Packaging these dynamically generated source files into a project allows us to debug the files by opening them up in Visual Studio in case something goes wrong.





 

Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Step By Step Guide to Detect Heap Corruption in Windows Easily

How to dynamically add Properties in C# .NET?