在运行时从CodeDOM编译中删除代码

时间:2014-07-02 01:50:17

标签: c# codedom

我有一个带有CheckBox和按钮的Windows窗体应用程序。按钮将使得CodeDOM编译的exe将禁用任务管理器。但如果他们不希望它禁用,他们可以取消选中该按钮。我试图做的是,如果他们取消选中该按钮,它将从禁用任务管理器的资源文件中删除代码块。

这是我的资源档案:

using System;
using System.Windows.Forms;
using Microsoft.Win32;

static class Program
{
    [STAThread]
    static void Main()
    {
        RegistryKey regkey;
        string keyValueInt = "1";
        string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";

        try
        {
            regkey = Registry.CurrentUser.CreateSubKey(subKey);
            regkey.SetValue("DisableTaskMgr", keyValueInt);
            regkey.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

我的主要代码:

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.CodeDom.Compiler;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string source = Properties.Resources.BaseSource;

            if (checkBox1.Checked == false)
            {
                // Not sure what to put here
            }

            CompilerResults results = null;

            using (SaveFileDialog sfd = new SaveFileDialog() { Filter =     "Executable|*.exe"})
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {                  
                    results = Build(source, sfd.FileName);
                }
            }

            if (results.Errors.Count > 0)
                foreach (CompilerError error in results.Errors)
                    Console.WriteLine("{0} at line {1}",
                        error.ErrorText, error.Line);
            else
                Console.WriteLine("Succesfully compiled!");

            Console.ReadLine();
        }

        private static CompilerResults Build(string source, string fileName)
        {       
            CompilerParameters parameters = new CompilerParameters()
            {
                GenerateExecutable = true,
                ReferencedAssemblies = { "System.dll", "System.Windows.Forms.dll" },
                OutputAssembly = fileName,
                TreatWarningsAsErrors = false
            };

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
            return provider.CompileAssemblyFromSource(parameters, source);
        }        
    }
}

1 个答案:

答案 0 :(得分:4)

不要自己替换部分源代码,而是让编译器通过利用条件编译符号为您完成。

您可以修改源文件以包含条件编译符号,例如DISABLETASKMGR,像这样:

using System;
using System.Windows.Forms;
using Microsoft.Win32;

static class Program
{
    [STAThread]
    static void Main()
    {
#if DISABLETASKMGR
        RegistryKey regkey;
        string keyValueInt = "1";
        string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";

        try
        {
            regkey = Registry.CurrentUser.CreateSubKey(subKey);
            regkey.SetValue("DisableTaskMgr", keyValueInt);
            regkey.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
#endif
    }
}

然后根据您的复选框是否已选中来设置CompilerOptions:

private static CompilerResults Build(string source, string fileName, bool disableTaskManager)
{
    CompilerParameters parameters = new CompilerParameters()
    {
        CompilerOptions = disableTaskManager ? "/define:DISABLETASKMGR" : "",
        GenerateExecutable = true,
        ReferencedAssemblies = { "System.dll", "System.Windows.Forms.dll" },
        OutputAssembly = fileName,
        TreatWarningsAsErrors = false
    };

    CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
    return provider.CompileAssemblyFromSource(parameters, source);
} 

这可能比基于文本替换或插入的解决方案更易于维护。当然,还有另一个选择是有两个源文件(一个带有可选代码,一个没有它),并根据用户选择的设置选择合适的源文件。