在不安装Visual Studio的情况下以编程方式即时创建csproj [英] Programmatically create a csproj on the fly without Visual Studio installed

查看:106
本文介绍了在不安装Visual Studio的情况下以编程方式即时创建csproj的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 MSBuild 命名空间以编程方式生成.csproj文件,但是缺少代码示例使此过程变得乏味且容易出错。

I am attempting to generate a .csproj file programatically using the MSBuild namespace, but the lack of code samples is making this a tedious and error prone process.

到目前为止,我已经获得了以下代码,但是我不确定如何向项目中添加类,引用等。

So far, I have got the following code but I am not sure how to add classes, references and such to the project.

public void Build()
{
    string projectFile = string.Format(@"{0}\{1}.csproj", Common.GetApplicationDataFolder(), _project.Target.AssemblyName);
    Microsoft.Build.Evaluation.Project p = new Microsoft.Build.Evaluation.Project();

    ProjectCollection pc = new ProjectCollection();

    Dictionary<string, string> globalProperty = new Dictionary<string, string>();

    globalProperty.Add("Configuration", "Debug");
    globalProperty.Add("Platform", "x64");

    BuildRequestData buildRequest = new BuildRequestData(projectFile, globalProperty, null, new string[] { "Build" }, null);

    p.Save(projectFile);

    BuildResult buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(pc), buildRequest);
}

谢谢。

推荐答案

如果您真的想使用MSBuild API创建proj文件,则必须使用Microsoft.Build.Construction命名空间。您将需要的大多数类型都在Micrsoft.Build.dll程序集中。一个简短的示例,该示例创建具有一些属性和项目组的项目文件:

If you really want to create a proj file with MSBuild API you have to use the Microsoft.Build.Construction namespace. Most of the types you will need are in the Micrsoft.Build.dll assembly. A short sample that creates a project file with a few properties and item groups:

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

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

        // items to compile
        AddItems(root, "Compile", "test.cs");

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

        root.Save("test.csproj");
        Console.WriteLine(File.ReadAllText("test.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);
        }
    }
}

请注意,这只会创建项目文件。它不会运行。此外,配置和平台之类的属性仅在Visual Studio生成的proj文件的上下文中才有意义。在这里,除非您按照Visual Studio自动执行的条件添加更多属性组,否则它们实际上不会做任何事情。

Note that this just creates the proj file. It doesn't run it. Also, properties like "Configuration" and "Platform" are only meaningful in the context of a proj file generated by Visual Studio. Here they won't really do anything unless you add more property groups with conditions the way Visual Studio does automatically.

就像我在评论中指出的那样,我认为这是错误的解决方法。您真的只想通过CodeDom进行动态源代码编译。

Like I indicated in my comments, I think this is wrong way to go about this. You really just want dynamic compilation of sources, which is available through CodeDom:

using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var provider = CodeDomProvider.CreateProvider("C#");
        string[] sources = {
                               @"public abstract class BaseClass { public abstract void Test(); }",
                               @"public class CustomGenerated : BaseClass { public override void Test() { System.Console.WriteLine(""Hello World""); } }"
                           };

        var results = provider.CompileAssemblyFromSource(new CompilerParameters() {
            GenerateExecutable = false,
            ReferencedAssemblies = { "System.dll", "System.Core.dll" },
            IncludeDebugInformation = true,
            CompilerOptions = "/platform:anycpu"
        }, sources);
        if (results.Errors.Count > 0)
        {
            Console.WriteLine("{0} errors", results.Errors.Count);
            foreach(CompilerError error in results.Errors)
            {
                Console.WriteLine("{0}: {1}", error.ErrorNumber, error.ErrorText);
            }
        }
        else
        {
            var type = results.CompiledAssembly.GetType("CustomGenerated");
            object instance = Activator.CreateInstance(type);
            type.GetMethod("Test").Invoke(instance, null);
        }
    }
}

这篇关于在不安装Visual Studio的情况下以编程方式即时创建csproj的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆