【问题标题】:How to pass a variable with CSharpCodeProvider?如何使用 CSharpCodeProvider 传递变量?
【发布时间】:2020-12-20 04:57:01
【问题描述】:

我需要使用我的应用程序创建一个 EXE 文件,我可以通过操纵字符串格式来传递字符串,但我无法将我需要的其他变量传递给 ex:byte 数组,如果这有帮助,这是我的代码:

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Windows;

namespace ACompiler.CompWorker
{
    class CompilerWorker
    {
        public static byte[] testarray = SomeClass.SomeArray;
        public static string Key = "Testkey12";
        public static void Compile()
        {
            CSharpCodeProvider CompileProvider = new CSharpCodeProvider();

            CompilerParameters CompileProviderParameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, AppDomain.CurrentDomain.BaseDirectory + "Compiled.exe", true);
            CompileProviderParameters.GenerateExecutable = true;


            string test= @"using System;

namespace Tests
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte[] Content = " + testarray + @";
                string Key = """ + Key + @""";
                Console.WriteLine(""Key: "" + EKey);
                Console.WriteLine(Content);
                Console.ReadLine();
            }
        }
    }
";

            var Result = CompileProvider.CompileAssemblyFromSource(CompileProviderParameters, test);
        }
    }
}

基本上我想将“testarray”移动到已编译的应用程序中,希望有人能指出我正确的方向!

【问题讨论】:

    标签: c# variables csharpcodeprovider


    【解决方案1】:

    诀窍是将数据“序列化”回编译器可以编译的代码。试试这个:

    var arrayCode = "new byte[] { " + string.Join(", ", testarray) + " }";
    
    string test = @"using System;
    namespace Tests
        {
            class Program
            {
                static void Main(string[] args)
                {
                    byte[] Content = " + arrayCode + @";
                    string Key = """ + Key + @""";
                    Console.WriteLine(""Key: "" + EKey);
                    foreach(byte b in Content)
                    {
                        Console.WriteLine(b.ToString());
                    }
                    Console.ReadLine();
                }
            }
        }
    ";
    

    请记住,您不能对字节数组对象执行Console.WriteLine 并让它吐出每个项目。您将不得不遍历这些项目以将它们打印出来。我更新了您的代码以正确的方式进行操作。

    【讨论】:

    • 它可以工作,但如果数组太大,我的程序就会冻结...
    • 没关系,我有一个显示“test”字符串的消息框,但它最终会太大而无法显示。哈哈
    猜你喜欢
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多