C# -----通过操作系统命令编译.cs 生成dll

C# -----通过操作系统命令编译.cs 生成dll

public class CodeDll
{

    public string DllName = "MyName.dll";

    public string CsFilePath = "Path";


    public string Compile()
    {
        string result = string.Empty;
        string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        Process process = new Process();

        //设置启动进程的属性
        process.StartInfo.FileName = "cmd.exe";

        //不使用操作系统的shell启动进程
        process.StartInfo.UseShellExecute = false;
        //设置应用程序的输入从Process.StandardInput 流中读取值
        process.StartInfo.RedirectStandardInput = true;

        //设置应用程序的文本输出写入Process.StandardOutput流中的值
        process.StartInfo.RedirectStandardOutput = true;
        
        //设置应用错误输出写入Process.StandardError流中的值
        process.StartInfo.RedirectStandardError = true;
        //设置在新窗口中启动该进程的值
        process.StartInfo.CreateNoWindow = true;
        process.Start();
        string value = string.Format("C:", Array.Empty<object>());
        //将字符串"C:"写入流
        process.StandardInput.WriteLine(value);
        value = string.Format("cd C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319", Array.Empty<object>());

        //将字符串 以上地址写入流
        process.StandardInput.WriteLine(value);

        //将.CS 生成dll 的命令行字符串
        StringBuilder stringBuilder = new StringBuilder();
        string text = baseDirectory  + this.DllName;
        string text2 = baseDirectory  + this.CsFilePath;
        string text3 = baseDirectory + "MM.xml";
        //bool flag = this.CsFilesList.Count == 0;

        bool flag=true;
        if (flag)
        {
            stringBuilder.Append(string.Concat(new string[]
            {
                    "csc /t:library /out:",
                    text,
                    "  ",
                    text2,
                    "\\*cs  /doc:",
                    text3
            }));
        }
        value = stringBuilder.ToString();
        process.StandardInput.WriteLine(value);
        Thread.Sleep(4000);
        process.StandardInput.WriteLine("exit");
        result = process.StandardOutput.ReadToEnd();
        string text4 = process.StandardError.ReadToEnd();
        process.StandardError.Close();
        bool flag2 = !string.IsNullOrEmpty(text4);
        if (flag2)
        {
            MessageBox.Show(text4);
        }
        return result;

    }
}

将所有想要生成dll 的.cs文件放置在Path 目录下, 调用以上方法,就可以生成MyName.dll 文件咯!
这是一个Demo,更多复杂的内容和实现方法,比如生成.exe.生成项目文件等,需要再研究哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值