当前位置: 首页>>代码示例>>C#>>正文


C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource方法代码示例

本文整理汇总了C#中Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource方法的典型用法代码示例。如果您正苦于以下问题:C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource方法的具体用法?C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource怎么用?C# Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CSharp.CSharpCodeProvider的用法示例。


在下文中一共展示了Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Compile

        public static Assembly Compile(string sourcecode, string[] references, CompileLanguage language = CompileLanguage.CSharp)
        {
            CodeDomProvider comp = null;
            switch (language)
            {
                case CompileLanguage.VisualBasic:
                    comp = new Microsoft.VisualBasic.VBCodeProvider();
                    break;
                case CompileLanguage.CSharp:
                default:
                    comp = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
            }
            CompilerParameters cp = new CompilerParameters();
            foreach (string reference in references)
            {
                cp.ReferencedAssemblies.Add(reference);
            }
            cp.GenerateInMemory = true;

            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sourcecode);
            if (cr.Errors.HasErrors)
            {
                string error = string.Empty;
                foreach (CompilerError err in cr.Errors)
                {
                    error += err.ErrorText + System.Environment.NewLine;
                }
                System.Diagnostics.Trace.WriteLine(error);
                return null;
            }

            return cr.CompiledAssembly;
        }
开发者ID:WrongDog,项目名称:Profiler,代码行数:34,代码来源:RefelctionEventHandler.cs

示例2: ParseString

        public static string ParseString(string input)
        {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
            };

            var code = @"
            namespace Tmp
            {
                public class TmpClass
                {
                    public static string GetValue()
                    {
                        return """ + input + @""";
                    }
                }
            }";

            var compileResult = provider.CompileAssemblyFromSource(parameters, code);

            if (compileResult.Errors.HasErrors)
            {
                return input;
                //throw new ArgumentException(compileResult.Errors.Cast<System.CodeDom.Compiler.CompilerError>().First(e => !e.IsWarning).ErrorText);
            }

            var asmb = compileResult.CompiledAssembly;
            var method = asmb.GetType("Tmp.TmpClass").GetMethod("GetValue");

            return method.Invoke(null, null) as string;
        }
开发者ID:simul,项目名称:cruise_control,代码行数:34,代码来源:Program.cs

示例3: Compile

        public static Assembly Compile(string sSource, string[] referencedAssemblies)
        {
            Microsoft.CSharp.CSharpCodeProvider comp = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            if (!PlatformDetector.IsUnix)
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""));
            }
            else
            {
                cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Replace("file://", ""));
            }
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            foreach (var assembly in referencedAssemblies)
            {

                cp.ReferencedAssemblies.Add(Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory
                    , assembly + ".dll"));
            }
            CompilerResults cr = comp.CompileAssemblyFromSource(cp, sSource);
            if (cr.Errors.HasErrors)
            {
                StringBuilder sError = new StringBuilder();
                sError.Append("Error Compiling Expression: ");
                foreach (CompilerError err in cr.Errors)
                    sError.AppendFormat("{0}\n", err.ErrorText);
                throw new ApplicationException("Ошибка компиляции выражения: " + sError.ToString() + "\n" + sSource);
            }
            return cr.CompiledAssembly;
        }
开发者ID:nico-izo,项目名称:KOIB,代码行数:32,代码来源:DynamicAssemblyHelper.cs

示例4: CompileScript

        //-----------------------------------------------------------------------------
        // Internal Methods
        //-----------------------------------------------------------------------------
        // Compile the final code for a script only to find any errors and/or warnings.
        private static ScriptCompileResult CompileScript(string code)
        {
            // Setup the compile options.
            CompilerParameters options	= new CompilerParameters();
            options.GenerateExecutable	= false; // We want a Dll (Class Library)
            options.GenerateInMemory	= true;

            // Add the assembly references.
            Assembly zeldaApiAssembly = Assembly.GetAssembly(typeof(ZeldaAPI.CustomScriptBase));
            options.ReferencedAssemblies.Add(zeldaApiAssembly.Location);

            // Create a C# code provider and compile the code.
            Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerResults csResult = csProvider.CompileAssemblyFromSource(options, code);

            // Copy warnings and errors into the ScriptComileResult.
            ScriptCompileResult result	= new ScriptCompileResult();
            foreach (CompilerError csError in csResult.Errors) {
                ScriptCompileError error = new ScriptCompileError(csError.Line,
                    csError.Column, csError.ErrorNumber, csError.ErrorText, csError.IsWarning);
                if (error.IsWarning)
                    result.Warnings.Add(error);
                else
                    result.Errors.Add(error);
            }

            return result;
        }
开发者ID:trigger-death,项目名称:ZeldaOracle,代码行数:32,代码来源:ScriptEditorCompiler.cs

示例5: createAssembly

        public static void createAssembly(string code)
        {
            string[] sources = { code };
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
            parameters.GenerateExecutable = (bool)launchArguments.flags["createbinary"];
            if ((bool)launchArguments.flags["createbinary"])
                parameters.OutputAssembly = IO.getExePath();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            parameters.ReferencedAssemblies.Add("System.Drawing.dll");

            using (Microsoft.CSharp.CSharpCodeProvider CodeProv =
            new Microsoft.CSharp.CSharpCodeProvider())
            {
                CompilerResults results = CodeProv.CompileAssemblyFromSource(parameters, sources);

                if (results.Errors.HasErrors)
                    debug.throwException("Compilation error", String.Join(Environment.NewLine, results.Errors.Cast<CompilerError>().Select(n => n.ToString())), debug.importance.Fatal);

                if (!(bool)launchArguments.flags["createbinary"])
                {
                    Console.WriteLine("Initializing ListSharp");

                    var type = results.CompiledAssembly.GetType("MainClass");
                    var obj = Activator.CreateInstance(type);
                    var output = type.GetMethod("Execute").Invoke(obj, new object[] { });
                    Console.WriteLine(output);
                }
            }
        }
开发者ID:timopomer,项目名称:ListSharp,代码行数:33,代码来源:compiler.cs

示例6: Execute

        public override object Execute(string code)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();
            CompilerParameters cmpParams = new System.CodeDom.Compiler.CompilerParameters();
            cmpParams.GenerateInMemory = true;
            cmpParams.GenerateExecutable = true;
            //cmpParams.CompilerOptions = "/t:exe";

            foreach (string ass in this._referencedAssemblies)
                cmpParams.ReferencedAssemblies.Add(ass+".dll");

            string codeString = this.GenerateReferenceString();
            codeString = this.InsertCode(code);

            CompilerResults results = compiler.CompileAssemblyFromSource(cmpParams, codeString);

            //			foreach (System.CodeDom.Compiler.CompilerError ce in results.Errors)
            //				this.Put(ce.ErrorText);

            if (results.Errors.Count == 0 && results.CompiledAssembly!=null)
            {
                System.Reflection.MethodInfo methodInfo = results.CompiledAssembly.EntryPoint;
                return methodInfo.Invoke(null, null);
            }
            return null;
        }
开发者ID:timdetering,项目名称:Endogine,代码行数:26,代码来源:ScripterCSharp.cs

示例7: Calculate

        /// <summary>
        /// 动态编译
        /// </summary>
        /// <param name="formula">需编译的内容</param>
        /// <param name="returnType">返回类型</param>
        /// <param name="obj">参数</param>
        /// <returns></returns>
        public static object Calculate(string formula, string returnType, object obj)
        {
            try
            {
                string paramExp = obj.GetType().ToString() + " obj";
                object calculated = null;

                Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
                System.CodeDom.Compiler.CompilerParameters parameter = new System.CodeDom.Compiler.CompilerParameters();
                parameter.ReferencedAssemblies.Add("System.dll");
                parameter.GenerateExecutable = false; //<--不要生成 EXE 文件
                parameter.GenerateInMemory = true; //在内存中运行
                string codeDom = GenerateCodeBlocks(formula, returnType, paramExp);
                System.CodeDom.Compiler.CompilerResults result = provider.CompileAssemblyFromSource(parameter,codeDom);//动态编译后的结果

                if (result.Errors.Count > 0)
                {
                    return null;
                }
                System.Reflection.MethodInfo newMethod = result.CompiledAssembly.GetType("Maike.Calculation").GetMethod("dowork");
                calculated = result.CompiledAssembly.GetType("Maike.Calculation").GetMethod("dowork").Invoke(null, new object[] { obj });

                return calculated;
            }
            catch
            {
                return null;
            }
        }
开发者ID:weiliji,项目名称:NFMT,代码行数:36,代码来源:Utility.cs

示例8: Main

        static void Main(string[] args)
        {
            CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();

            string[] assemblyNames = new string[]{
                "mscorlib.dll",
                "System.dll",
                "System.Data.dll",
                "System.Drawing.dll",
                "System.Xml.dll",
                "System.Core.dll",
                "System.Windows.Forms.dll"
            };

            CompilerParameters compilerParameters = new CompilerParameters(assemblyNames){
                OutputAssembly = "OutputAssembly.dll",
                GenerateExecutable = false,
                GenerateInMemory = true,
                WarningLevel = 3,
                CompilerOptions = "/optimize",
                IncludeDebugInformation = false,
                //TempFiles = new TempFileCollection(".", true)
            };

            CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(
                compilerParameters,
                new string[] { Code });

            /* This prints low-level messages like this, as well as error messages:
                *
                * G:\tmp\CsCompilerTest\WorkingDir> "C:\Windows\Microsoft.NET\Framework\v4.0.30319
                * \csc.exe" /t:library /utf8output /out:"C:\Users\Adam Sawicki\AppData\Local\Temp\
                * 0pdzupen.dll" /debug- /optimize+ /w:3 /optimize  "C:\Users\Adam Sawicki\AppData\
                * Local\Temp\0pdzupen.0.cs"

                * Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
                * Copyright (C) Microsoft Corporation. All rights reserved.
                */
            foreach (String message in compilerResults.Output)
                Console.WriteLine(message);

            /* This prints error messages in form of:
                *
                * c:\Users\Adam Sawicki\AppData\Local\Temp\4kbqoyz2.0.cs(7,9) : error CS0103: The
                * name 'Console' does not exist in the current context
                */
            //foreach (CompilerError error in compilerResults.Errors)
            //    Console.WriteLine(error.ToString());

            Assembly assembly = compilerResults.CompiledAssembly;
            if (assembly == null) return;

            object obj = assembly.CreateInstance("MainClass");
            if (obj == null) return;

            Type type = obj.GetType();
            type.InvokeMember("Main", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, obj, new object[] { });
        }
开发者ID:sawickiap,项目名称:NoConsole,代码行数:58,代码来源:Program.cs

示例9: CreateAssemblyFromSourceCode

        public Assembly CreateAssemblyFromSourceCode(string extension, IList references, params string[] sourcecode)
        {
            compilerErrors = null;


            CodeDomProvider codeProvider = null;
            switch (extension.ToLower())
            {
                case ".cs":
                    codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                case ".vb":
                    codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                    break;
                default:
                    throw new InvalidOperationException("Script files must have a .cs or .vb.");
            }

            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.CompilerOptions = "/target:library /optimize";
            compilerParams.GenerateExecutable = false;
            compilerParams.GenerateInMemory = true;
            compilerParams.IncludeDebugInformation = false;

            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");


            foreach (string reference in references)
            {
                if (!compilerParams.ReferencedAssemblies.Contains(reference))
                {
                    compilerParams.ReferencedAssemblies.Add(reference);
                }
            }
            CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParams, sourcecode);


            if (results.Errors.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError item in results.Errors)
                {
                    sb.AppendFormat("{0} line:{1}   {2}\r\n", item.FileName, item.Line, item.ErrorText);
                }
                compilerErrors = results.Errors;
                throw new Exception(
                    "Compiler error(s)\r\n" + sb.ToString());
            }

            Assembly createdAssembly = results.CompiledAssembly;

            return createdAssembly;
        }
开发者ID:qcjxberin,项目名称:ec,代码行数:54,代码来源:AssemblyLoad.cs

示例10: ASLMethod

        public ASLMethod(String code)
        {
            using (var provider =
                new Microsoft.CSharp.CSharpCodeProvider())
            {
                var builder = new StringBuilder();
                builder
                    .AppendLine("using System;")
                    .AppendLine("using System.Collections.Generic;")
                    .AppendLine("using System.Linq;")
                    .AppendLine("using System.Reflection;")
                    .AppendLine("using System.Text;")
                    .AppendLine("public class CompiledScript")
                    .AppendLine("{")
                        .AppendLine("public dynamic Execute(dynamic timer, dynamic old, dynamic current)")
                        .AppendLine("{")
                            .Append(code)
                            .Append("return null;")
                        .AppendLine("}")
                    .AppendLine("}");

                var parameters = new System.CodeDom.Compiler.CompilerParameters()
                    {
                        GenerateInMemory = true,
                        CompilerOptions = "/optimize",
                    };
                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
                parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");

                var res = provider.CompileAssemblyFromSource(parameters, builder.ToString());

                if (res.Errors.HasErrors)
                {
                    var errorMessage = "";
                    foreach (var error in res.Errors)
                    {
                        errorMessage += error + "\r\n";
                    }
                    throw new ArgumentException(errorMessage, "code");
                }

                var type = res.CompiledAssembly.GetType("CompiledScript");
                CompiledCode = Activator.CreateInstance(type);
            }
        }
开发者ID:sirgebet,项目名称:LiveSplit.ScriptableAutoSplit,代码行数:52,代码来源:ASLMethod.cs

示例11: Compile

        // Compile all the scripts into one assembly.
        public ScriptCompileResult Compile(string code)
        {
            ScriptCompileResult result	= new ScriptCompileResult();
            string pathToAssembly = "";
            bool hasErrors = false;

            // Setup the compile options.
            CompilerParameters options	= new CompilerParameters();
            options.GenerateExecutable	= false;	// We want a Dll (Class Library)
            options.GenerateInMemory	= false;	// Save the assembly to a file.
            options.OutputAssembly		= "ZWD2CompiledScript.dll";

            // Add the assembly references.
            options.ReferencedAssemblies.Add(GetZeldaAPIAssembly().Location);

            // Create a C# code provider and compile the code.
            // The 'using' statement is necessary so the created DLL file isn't
            // locked when we try to load its contents.
            using (Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider()) {
                CompilerResults csResult = csProvider.CompileAssemblyFromSource(options, code);
                pathToAssembly	= csResult.PathToAssembly;
                hasErrors		= csResult.Errors.HasErrors;

                // Copy warnings and errors into the ScriptComileResult result.
                foreach (CompilerError csError in csResult.Errors) {
                    ScriptCompileError error = new ScriptCompileError(csError.Line,
                        csError.Column, csError.ErrorNumber, csError.ErrorText, csError.IsWarning);
                    if (error.IsWarning)
                        result.Warnings.Add(error);
                    else
                        result.Errors.Add(error);
                }
            }

            // If the compile was successful, then load the created.
            // DLL file into memory and then delete the file.
            if (!hasErrors) {
                result.RawAssembly = File.ReadAllBytes(pathToAssembly);
                //rawAssembly = result.RawAssembly;
                File.Delete(pathToAssembly);
            }
            else {
                //rawAssembly = null;
            }

            return result;
        }
开发者ID:trigger-death,项目名称:ZeldaOracle,代码行数:48,代码来源:ScriptManager.cs

示例12: Main

        public static void Main(string[] args)
        {
            List<string> sources = new List<string>();
            string cscode = "using System.Windows.Forms;\n";
            foreach (string filename in args)
            {
                if (filename.EndsWith(".wtf"))
                {
                    WindowsTextFoundation.Core.WindowsTextFoundation wtf = WindowsTextFoundation.Core.WindowsTextFoundation.FromFile(filename);
                    cscode += @"namespace WTFCSharp
{
public class WTFCSharp
{
public WTFCSharp()" + "\r\n{\r\n" +
                        wtf.Objects[0].ToCSharp() +
@"frm.ShowDialog();" +  //FIXME: INJECT INTO C# CODE
@"}
}
}";
                }
                else 
                {
                    sources.Add(System.IO.File.ReadAllText(filename));
                }
            }
            sources.Add(cscode);
            Console.WriteLine(cscode);
            Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Drawing.dll");
            cp.GenerateExecutable = true;
            cp.OutputAssembly = "wtfcs.exe";
            cp.MainClass = "WTFCSharpTest.a"; //FIXME
            CompilerResults r = csc.CompileAssemblyFromSource(cp,sources.ToArray());
            if (r.Errors.Count != 0)
            {
                foreach (CompilerError err in r.Errors)
                {
                    Console.WriteLine(err.ToString());
                }
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
开发者ID:mlnlover11,项目名称:MP.LSharp,代码行数:46,代码来源:Program.cs

示例13: Main

        static void Main()
        {
            var s = @"using System.CodeDom.Compiler;using System.Diagnostics;class P{static void Main(){var s = {0}{1}{0};var t = ;using (var p = new Microsoft.CSharp.CSharpCodeProvider()){var o = new CompilerParameters(new string[] { ""System.dll"" }) { GenerateExecutable = true };t = p.CompileAssemblyFromSource(o, s).PathToAssembly;}var i = new ProcessStartInfo(t) { UseShellExecute = false, CreateNoWindow = true };System.IO.File.Delete(t);}}";
            s = string.Format(s, s, '"');

            var t = "";
            using (var p = new Microsoft.CSharp.CSharpCodeProvider())
            {
                var o = new CompilerParameters(new string[] { "System.dll" }) { GenerateExecutable = true };
                var r = p.CompileAssemblyFromSource(o, s);
                t = r.PathToAssembly;
            }

            var i = new ProcessStartInfo(t) { UseShellExecute = false, CreateNoWindow = true };
            Process.Start(i).WaitForExit();
            System.IO.File.Delete(t);
        }
开发者ID:KvanTTT,项目名称:Freaky-Sources,代码行数:17,代码来源:SelfCompiliedProgram.cs

示例14: CreateAssembly

        public static Assembly CreateAssembly(string name)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();

            string source = LoadSource(name);

            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = false;
            options.OutputAssembly = name+".dll";
            options.ReferencedAssemblies.Add("MbUnit.Framework.dll");

            CompilerResults results = compiler.CompileAssemblyFromSource(options, source);
            if (results.Errors.HasErrors)
                CompilerAssert.DisplayErrors(results, Console.Out);
            Assert.IsFalse(results.Errors.HasErrors);
            return results.CompiledAssembly;
        }
开发者ID:BackupTheBerlios,项目名称:mbunit-svn,代码行数:18,代码来源:AssemblyCompiler.cs

示例15: CreateAssembly

        private static string CreateAssembly(string assemblyPath)
        {
            ICodeCompiler compiler = new Microsoft.CSharp.CSharpCodeProvider().CreateCompiler();

            string source = LoadSource(Path.GetFileNameWithoutExtension(assemblyPath));

            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = false;
            options.OutputAssembly = assemblyPath;
            options.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(assemblyPath) ,"MbUnit.Framework.dll"));

            CompilerResults results = compiler.CompileAssemblyFromSource(options, source);
            if (results.Errors.HasErrors)
                CompilerAssert.DisplayErrors(results, Console.Out);
            Assert.IsFalse(results.Errors.HasErrors);
            return results.PathToAssembly;
        }
开发者ID:timonela,项目名称:mb-unit,代码行数:18,代码来源:AssemblyCompiler.cs


注:本文中的Microsoft.CSharp.CSharpCodeProvider.CompileAssemblyFromSource方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。