c# msbuild.exe编译代码实例,编译生成代码
msbuild.exe编译代码实例
cmd执行语句
@echo off
C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe "H:\WQB\SBCERP2\trunk-new\SBC.sln" /t:rebuild /p:Configuration=Debug
解释:
/t:rebuild 重新生成
/t:build 生成
/t:clean 清理
/p:Configuration=Debug 编译模式:debug
/p:Configuration=release 编译模式:release
引用:
Newtonsoft.Json.dll json序列化
BackgroundWorker 后台进程
实例代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Threading;
namespace MsbuildTest
{
public partial class Form1 : Form
{
string outDic = "";
BackgroundWorker backgroundworker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
this.btnbulid.Click += btnbulid_Click;
this.btnpublish.Click += btnpublish_Click;
this.btnoutputpath.Click += btnoutputpath_Click;
this.btnsaveconfig.Click += btnsaveconfig_Click;
this.btnreadconfig.Click += btnreadconfig_Click;
this.btnclean.Click += btnclean_Click;
this.txtpath.AllowDrop = true;
this.txtpath.DragEnter += txtpath_DragEnter;
this.btnexit.Click += btnexit_Click;
this.btnsourcepath.Click += btnsourcepath_Click;
this.progressBar1.Visible = false;
backgroundworker.WorkerSupportsCancellation = true;//是否支持异步取消
backgroundworker.WorkerReportsProgress = true;//是否报告进度更新,这个属性很重要,必须启用才能对进度进行报告
backgroundworker.DoWork += backgroundworker_DoWork;
backgroundworker.ProgressChanged += backgroundworker_ProgressChanged;
backgroundworker.RunWorkerCompleted += backgroundworker_RunWorkerCompleted;
}
#region 事件
/// <summary>
/// 退出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnexit_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
}
/// <summary>
/// 停止异步编译
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnstop_Click(object sender, EventArgs e)
{
backgroundworker.CancelAsync();
this.progressBar1.Visible = false;
}
/// <summary>
/// 拖拽事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void txtpath_DragEnter(object sender, DragEventArgs e)
{
Array file = (System.Array)e.Data.GetData(DataFormats.FileDrop);
string fileText = null;
foreach (object I in file)
{
fileText += I.ToString();
fileText += "\n";
}
(sender as RichTextBox).Text = fileText;
}
/// <summary>
/// 清除输出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnclean_Click(object sender, EventArgs e)
{
this.txtresult.Text = "";
}
/// <summary>
/// 读取设置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnreadconfig_Click(object sender, EventArgs e)
{
ReadConfigModel();
}
/// <summary>
/// 保存设置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnsaveconfig_Click(object sender, EventArgs e)
{
SaveConfigModel();
}
/// <summary>
/// 打开输出文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnoutputpath_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(outDic))
{
outDic = IOHelper.CurDir;
}
if (Directory.Exists(outDic) == false)
{
Directory.CreateDirectory(outDic);
}
System.Diagnostics.Process.Start("explorer", outDic);
}
/// <summary>
/// 打开代码文件夹
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnsourcepath_Click(object sender, EventArgs e)
{
var config = GetConfigModel();
if (string.IsNullOrEmpty(config.url))
return;
if (File.Exists(config.url) == false)
return;
var directory = System.IO.Path.GetDirectoryName(config.url);
System.Diagnostics.Process.Start("explorer", directory);
}
/// <summary>
/// 发布
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnpublish_Click(object sender, EventArgs e)
{
if (backgroundworker.IsBusy)
return;
var random = new Random();
outDic = IOHelper.CurDir + DateTime.Now.ToString("yyyyMMdd") + "_" + random.Next(1000).ToString().PadLeft(8, '0');
if (Directory.Exists(outDic) == false)
{
Directory.CreateDirectory(outDic);
}
var config = GetConfigModel();
config.outputurl = outDic;
progressBar1.Visible = true;
var param = new BackGoundWorkerArgsModel();
param.Name = "1";
param.Args = config;
backgroundworker.RunWorkerAsync(param);
}
/// <summary>
/// 编译
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnbulid_Click(object sender, EventArgs e)
{
if (backgroundworker.IsBusy)
return;
var config = GetConfigModel();
progressBar1.Visible = true;
var param = new BackGoundWorkerArgsModel();
param.Name = "2";
param.Args = GetConfigModel();
backgroundworker.RunWorkerAsync(param);
}
void backgroundworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
{
(sender as BackgroundWorker).ReportProgress(10);
var result = new BackGoundWorkerResultModel();
var param = e.Argument as BackGoundWorkerArgsModel;
if (param != null)
{
result.Name = param.Name;
if (param.Name == "1")
{
var config = param.Args as ConfigModel;
var cmd = "";
var output = "";
cmd += "@echo off";
cmd += "\r\n";
cmd = string.Format("{0} \"{1}\" /t:rebuild /p:Configuration={2} /p:OutDir=\"{3}\"", config.versionurl, config.url.Replace("\0", ""), config.modelname, config.outputurl);
CmdHelper.RunCmd(cmd, out output);
result.Result = output;
}
if (param.Name == "2")
{
var config = param.Args as ConfigModel;
var cmd = "";
var output = "";
cmd += "@echo off";
cmd += "\r\n";
cmd += string.Format("{0} \"{1}\" /t:rebuild /p:Configuration={2}", config.versionurl, config.url.Replace("\0", ""), config.modelname);
CmdHelper.RunCmd(cmd, out output);
result.Result = output;
}
}
e.Result = result;
}
void backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
var result = e.Result as BackGoundWorkerResultModel;
if (result != null)
{
this.txtresult.Text = result.Result.ToString();
this.txtresult.SelectionStart = this.txtresult.Text.Length;
this.txtresult.Focus();
}
}
/// <summary>
/// 窗口加载完成
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Form1_Load(object sender, EventArgs e)
{
BindVesion();
BindModel();
ReadConfigModel();
}
/// <summary>
/// 获取版本号
/// </summary>
private void BindVesion()
{
//获取所有版本号
//C:\Windows\Microsoft.NET\Framework
var exename = "MSBuild.exe";
var files32 = IOHelper.FindFile(@"C:\Windows\Microsoft.NET\Framework", exename, "v*");
var files64 = IOHelper.FindFile(@"C:\Windows\Microsoft.NET\Framework64", exename, "v*");
var dataSource = new List<ComboItemModel>();
GetVersion(files32, dataSource, false);
GetVersion(files64, dataSource, true);
this.ddlversion.DisplayMember = "Value";
this.ddlversion.ValueMember = "Key";
this.ddlversion.DataSource = dataSource;
}
/// <summary>
/// 解析版本号
/// </summary>
/// <param name="files"></param>
/// <param name="dataSource"></param>
/// <param name="is64"></param>
private static void GetVersion(List<string> files, List<ComboItemModel> dataSource, bool is64 = false)
{
if (files.Count() > 0)
{
foreach (var fileurl in files)
{
var arr = fileurl.Split(new string[] { "\\", "/" }, StringSplitOptions.RemoveEmptyEntries);
if (arr.Length > 3)
{
var version = arr[arr.Length - 2];
version += is64 ? "(x64)" : "(x86)";
var model = new ComboItemModel(version, version, fileurl);
dataSource.Add(model);
}
}
}
}
/// <summary>
/// 获取编译模式
/// </summary>
private void BindModel()
{
var dataSource = new List<ComboItemModel>();
//编译模式
dataSource.Add(new ComboItemModel("1", "Debug"));
dataSource.Add(new ComboItemModel("2", "Release"));
this.ddlmode.DisplayMember = "Value";
this.ddlmode.ValueMember = "Key";
this.ddlmode.DataSource = dataSource;
}
/// <summary>
/// 保存设置
/// </summary>
private void SaveConfigModel()
{
var config = GetConfigModel();
IOHelper.SaveProcess(JsonConvert.SerializeObject(config), "config");
}
/// <summary>
/// 获取当前设置
/// </summary>
/// <returns></returns>
private ConfigModel GetConfigModel()
{
var config = new ConfigModel();
config.url = this.txtpath.Text.Trim();
//
var versionitem = this.ddlversion.SelectedItem as ComboItemModel;
if (versionitem != null)
{
config.version = versionitem.Key;
config.versionurl = versionitem.Tag;
}
//
var modelitem = this.ddlmode.SelectedItem as ComboItemModel;
if (modelitem != null)
{
config.model = modelitem.Key;
config.modelname = modelitem.Value;
}
return config;
}
/// <summary>
/// 读取设置
/// </summary>
private void ReadConfigModel()
{
try
{
var configstring = IOHelper.fileToString(IOHelper.CurDir + "config.txt");
if (string.IsNullOrEmpty(configstring))
return;
var config = JsonConvert.DeserializeObject<ConfigModel>(configstring);
if (config == null)
return;
this.txtpath.Text = config.url;
try
{
this.ddlversion.SelectedValue = config.version;
}
catch (Exception) { }
try
{
this.ddlmode.SelectedValue = config.model;
}
catch (Exception) { }
}
catch (Exception)
{
}
}
#endregion
}
}