我试图使用MSBuild命名空间以编程方式生成.csproj文件,但缺少代码示例使得这个过程变得繁琐且容易出错.
到目前为止,我有以下代码,但我不知道如何将类,引用等添加到项目中.
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程序集中.一个简短的示例,它创建一个包含一些属性和项目组的项目文件:
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); } } }
请注意,这只是创建proj文件.它没有运行它.此外,“配置”和“平台”等属性仅在Visual Studio生成的proj文件的上下文中有意义.除非您按照Visual Studio自动执行的方式添加更多具有条件的属性组,否则它们不会真正执行任何操作.
就像我在评论中指出的那样,我认为这是错误的做法.您真的只想要动态编译源代码,这可以通过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); } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。