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

实例代码
界面


Form1
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
    }
}

Form1.Designer.cs

namespace MsbuildTest
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnbulid = new System.Windows.Forms.Button();
            this.btnpublish = new System.Windows.Forms.Button();
            this.btnoutputpath = new System.Windows.Forms.Button();
            this.txtresult = new System.Windows.Forms.RichTextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.txtpath = new System.Windows.Forms.RichTextBox();
            this.ddlversion = new System.Windows.Forms.ComboBox();
            this.ddlmode = new System.Windows.Forms.ComboBox();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.btnsaveconfig = new System.Windows.Forms.Button();
            this.btnreadconfig = new System.Windows.Forms.Button();
            this.btnclean = new System.Windows.Forms.Button();
            this.progressBar1 = new System.Windows.Forms.ProgressBar();
            this.btnexit = new System.Windows.Forms.Button();
            this.btnsourcepath = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // btnbulid
            // 
            this.btnbulid.Location = new System.Drawing.Point(523, 88);
            this.btnbulid.Name = "btnbulid";
            this.btnbulid.Size = new System.Drawing.Size(75, 51);
            this.btnbulid.TabIndex = 0;
            this.btnbulid.Text = "编译";
            this.btnbulid.UseVisualStyleBackColor = true;
            // 
            // btnpublish
            // 
            this.btnpublish.Location = new System.Drawing.Point(614, 87);
            this.btnpublish.Name = "btnpublish";
            this.btnpublish.Size = new System.Drawing.Size(75, 51);
            this.btnpublish.TabIndex = 1;
            this.btnpublish.Text = "发布";
            this.btnpublish.UseVisualStyleBackColor = true;
            // 
            // btnoutputpath
            // 
            this.btnoutputpath.Location = new System.Drawing.Point(707, 87);
            this.btnoutputpath.Name = "btnoutputpath";
            this.btnoutputpath.Size = new System.Drawing.Size(75, 51);
            this.btnoutputpath.TabIndex = 2;
            this.btnoutputpath.Text = "打开输出文件夹";
            this.btnoutputpath.UseVisualStyleBackColor = true;
            // 
            // txtresult
            // 
            this.txtresult.Location = new System.Drawing.Point(80, 204);
            this.txtresult.Name = "txtresult";
            this.txtresult.Size = new System.Drawing.Size(714, 362);
            this.txtresult.TabIndex = 3;
            this.txtresult.Text = "";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 204);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(59, 12);
            this.label1.TabIndex = 4;
            this.label1.Text = "输出结果:";
            // 
            // txtpath
            // 
            this.txtpath.Location = new System.Drawing.Point(113, 9);
            this.txtpath.Name = "txtpath";
            this.txtpath.Size = new System.Drawing.Size(427, 63);
            this.txtpath.TabIndex = 6;
            this.txtpath.Text = "";
            // 
            // ddlversion
            // 
            this.ddlversion.FormattingEnabled = true;
            this.ddlversion.Location = new System.Drawing.Point(146, 103);
            this.ddlversion.Name = "ddlversion";
            this.ddlversion.Size = new System.Drawing.Size(121, 20);
            this.ddlversion.TabIndex = 7;
            // 
            // ddlmode
            // 
            this.ddlmode.FormattingEnabled = true;
            this.ddlmode.Location = new System.Drawing.Point(356, 103);
            this.ddlmode.Name = "ddlmode";
            this.ddlmode.Size = new System.Drawing.Size(121, 20);
            this.ddlmode.TabIndex = 8;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(78, 106);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(53, 12);
            this.label3.TabIndex = 9;
            this.label3.Text = ".net版本";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(284, 106);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 12);
            this.label4.TabIndex = 10;
            this.label4.Text = "编译模式";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 9);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(95, 12);
            this.label2.TabIndex = 11;
            this.label2.Text = "解决方案(*.sln)";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(13, 40);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(89, 12);
            this.label5.TabIndex = 12;
            this.label5.Text = "项目(*.csproj)";
            // 
            // btnsaveconfig
            // 
            this.btnsaveconfig.Location = new System.Drawing.Point(638, 12);
            this.btnsaveconfig.Name = "btnsaveconfig";
            this.btnsaveconfig.Size = new System.Drawing.Size(75, 40);
            this.btnsaveconfig.TabIndex = 13;
            this.btnsaveconfig.Text = "保存设置";
            this.btnsaveconfig.UseVisualStyleBackColor = true;
            // 
            // btnreadconfig
            // 
            this.btnreadconfig.Location = new System.Drawing.Point(719, 13);
            this.btnreadconfig.Name = "btnreadconfig";
            this.btnreadconfig.Size = new System.Drawing.Size(75, 39);
            this.btnreadconfig.TabIndex = 14;
            this.btnreadconfig.Text = "读取设置";
            this.btnreadconfig.UseVisualStyleBackColor = true;
            // 
            // btnclean
            // 
            this.btnclean.Location = new System.Drawing.Point(800, 529);
            this.btnclean.Name = "btnclean";
            this.btnclean.Size = new System.Drawing.Size(59, 37);
            this.btnclean.TabIndex = 15;
            this.btnclean.Text = "清空";
            this.btnclean.UseVisualStyleBackColor = true;
            // 
            // progressBar1
            // 
            this.progressBar1.Location = new System.Drawing.Point(15, 235);
            this.progressBar1.Name = "progressBar1";
            this.progressBar1.Size = new System.Drawing.Size(51, 23);
            this.progressBar1.TabIndex = 16;
            // 
            // btnexit
            // 
            this.btnexit.Location = new System.Drawing.Point(800, 13);
            this.btnexit.Name = "btnexit";
            this.btnexit.Size = new System.Drawing.Size(59, 39);
            this.btnexit.TabIndex = 15;
            this.btnexit.Text = "退出";
            this.btnexit.UseVisualStyleBackColor = true;
            // 
            // btnsourcepath
            // 
            this.btnsourcepath.Location = new System.Drawing.Point(546, 13);
            this.btnsourcepath.Name = "btnsourcepath";
            this.btnsourcepath.Size = new System.Drawing.Size(86, 39);
            this.btnsourcepath.TabIndex = 2;
            this.btnsourcepath.Text = "打开代码文件夹";
            this.btnsourcepath.UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(871, 601);
            this.Controls.Add(this.progressBar1);
            this.Controls.Add(this.btnexit);
            this.Controls.Add(this.btnclean);
            this.Controls.Add(this.btnreadconfig);
            this.Controls.Add(this.btnsaveconfig);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.ddlmode);
            this.Controls.Add(this.ddlversion);
            this.Controls.Add(this.txtpath);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtresult);
            this.Controls.Add(this.btnsourcepath);
            this.Controls.Add(this.btnoutputpath);
            this.Controls.Add(this.btnpublish);
            this.Controls.Add(this.btnbulid);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button btnbulid;
        private System.Windows.Forms.Button btnpublish;
        private System.Windows.Forms.Button btnoutputpath;
        private System.Windows.Forms.RichTextBox txtresult;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.RichTextBox txtpath;
        private System.Windows.Forms.ComboBox ddlversion;
        private System.Windows.Forms.ComboBox ddlmode;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Button btnsaveconfig;
        private System.Windows.Forms.Button btnreadconfig;
        private System.Windows.Forms.Button btnclean;
        private System.Windows.Forms.ProgressBar progressBar1;
        private System.Windows.Forms.Button btnexit;
        private System.Windows.Forms.Button btnsourcepath;
    }
}

IOHelper.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MsbuildTest
{
    /// <summary>
    /// 文件存储类
    /// </summary>
    public class IOHelper
    {
        public static string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir\";

        /// <summary>  
        /// 获取文件中的数据串  
        /// </summary>  
        public static string fileToString(String filePath)
        {
            string str = "";

            //获取文件内容  
            if (System.IO.File.Exists(filePath))
            {
                System.IO.StreamReader file1 = new System.IO.StreamReader(filePath);//读取文件中的数据  
                str = file1.ReadToEnd();                                            //读取文件中的全部数据  

                file1.Close();
                file1.Dispose();
            }
            return str;
        }
        // <summary>  
        /// 保存数据data到文件处理过程,返回值为保存的文件名  
        /// </summary>  
        public static String SaveProcess(String data, String name)
        {
            if (!System.IO.Directory.Exists(CurDir)) System.IO.Directory.CreateDirectory(CurDir);   //该路径不存在时,在当前文件目录下创建文件夹"导出.."  

            //不存在该文件时先创建  
            String filePath = CurDir + name + ".txt";
            System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false);     //文件已覆盖方式添加内容  

            file1.Write(data);                                                              //保存数据到文件  

            file1.Close();                                                                  //关闭文件  
            file1.Dispose();                                                                //释放对象  

            return filePath;
        }

        /// <summary>
        /// 搜索指定文件夹下的文件
        /// </summary>
        /// <param name="sSourcePath"></param>
        /// <param name="searchpara">文件名过滤条件</param>
        /// /// <param name="searchpara">文件夹过滤条件</param>
        /// <returns></returns>
        public static List<string> FindFile(string sSourcePath, string searchpara = "*.*", string pathsearchpara = "")
        {
            List<String> list = new List<string>();
            //遍历文件夹
            DirectoryInfo theFolder = new DirectoryInfo(sSourcePath);
            FileInfo[] thefileInfo = theFolder.GetFiles(searchpara, SearchOption.TopDirectoryOnly);
            foreach (FileInfo NextFile in thefileInfo)  //遍历文件
                list.Add(NextFile.FullName);

            //遍历子文件夹
            DirectoryInfo[] dirInfo = theFolder.GetDirectories(pathsearchpara);
            foreach (DirectoryInfo NextFolder in dirInfo)
            {
                var tmpfile = FindFile(NextFolder.FullName, searchpara, pathsearchpara);
                list.AddRange(tmpfile);
            }

            return list;

        }
    }
}

CmdHelper.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MsbuildTest
{
    /// <summary>
    /// cmd类
    /// </summary>
    public class CmdHelper
    {
        private static string CmdPath = @"C:\Windows\System32\cmd.exe";

        /// <summary>
        /// 执行cmd命令
        /// 多命令请使用批处理命令连接符:
        /// <![CDATA[
        /// &:同时执行两个命令
        /// |:将上一个命令的输出,作为下一个命令的输入
        /// &&:当&&前的命令成功时,才执行&&后的命令
        /// ||:当||前的命令失败时,才执行||后的命令]]>
        /// 其他请百度
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="output"></param>
        public static void RunCmd(string cmd, out string output)
        {
            cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
            using (Process p = new Process())
            {
                p.StartInfo.FileName = CmdPath;
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口写入命令
                p.StandardInput.WriteLine(cmd);
                p.StandardInput.AutoFlush = true;

                //获取cmd窗口的输出信息
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
        }
    }
}

ComboItemModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MsbuildTest
{

    /// <summary>
    /// 下拉框选项
    /// </summary>
    public class ComboItemModel
    {
        public ComboItemModel()
        {
        }
        public ComboItemModel(string Key, string Value, string Tag = "")
        {
            this.Key = Key;
            this.Value = Value;
            this.Tag = Tag;
        }

        public string Key { get; set; }
        public string Value { get; set; }
        public string Tag { get; set; }
    }
}

ConfigModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MsbuildTest
{

    /// <summary>
    /// 保存设置Model
    /// </summary>
    public class ConfigModel
    {
        /// <summary>
        /// 解决方案地址
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// .net版本号
        /// </summary>
        public string version { get; set; }
        /// <summary>
        /// .net版本exe地址
        /// </summary>
        public string versionurl { get; set; }
        /// <summary>
        /// 编译模式key
        /// </summary>
        public string model { get; set; }
        /// <summary>
        /// 编译模式文字
        /// </summary>
        public string modelname { get; set; }
        /// <summary>
        /// 输出文件夹
        /// </summary>
        public string outputurl { get; set; }
    }
}

BackGoundWorkerArgsModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MsbuildTest
{
    /// <summary>
    /// BackGoundWorkerArgs参数
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BackGoundWorkerArgsModel
    {
        public string Name { get; set; }
        public object Args { get; set; }
    }
}

BackGoundWorkerResultModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MsbuildTest
{
    /// <summary>
    /// BackGoundWorkerArgs返回值
    /// </summary>
    public class BackGoundWorkerResultModel
    {
        public string Name { get; set; }
        public object Result { get; set; }
    }
}

完结!



猜你喜欢

转载自www.cnblogs.com/a735882640/p/9210328.html
今日推荐