未处理的异常:System.BadImageFormatException:无法加载从RoslynCompileSample加载的文件或程序集'0字节,

问题描述 投票:0回答:1

我正在尝试使用Roslyn Compiler创建一个类的实例。但是它抛出了错误:代码是:

namespace CSharptoJSON.Controllers
{
    public class InstanceCreator
    {

        /// Compiles C# code and creates instances of object types
        /// <returns>Collection of object instances</returns>
        public static IEnumerable<object> CompileClasses(string csharp)
        {
            if (string.IsNullOrEmpty(csharp))
            {
                throw new ArgumentNullException(nameof(csharp));
            }


            SyntaxTree tree = CSharpSyntaxTree.ParseText(csharp);
            // CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
           CompilationUnitSyntax root = (CompilationUnitSyntax) tree.GetRoot();

            // add Using statements to syntax tree
            var system = SyntaxFactory.IdentifierName("System");
            var systemCollections = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Collections"));
            var systemCollectionsGeneric = SyntaxFactory.QualifiedName(systemCollections, SyntaxFactory.IdentifierName("Generic"));
            var systemLinq = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Linq"));
            var systemText = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Text"));
            var systemXml = SyntaxFactory.QualifiedName(system, SyntaxFactory.IdentifierName("Xml"));

            var declaredUsings = root.Usings.Select(x => x.Name.ToString()).ToList();
            if (!declaredUsings.Contains("System"))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(system).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Collections"))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(systemCollections).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Collections.Generic"))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(systemCollectionsGeneric).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Linq"))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(systemText).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Text"))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(systemLinq).NormalizeWhitespace());
            }
            if (!declaredUsings.Contains("System.Xml"))
            {
                root = root.AddUsings(SyntaxFactory.UsingDirective(systemXml).NormalizeWhitespace());
            }

            tree = CSharpSyntaxTree.Create(root);
            root = tree.GetCompilationUnitRoot();

            Console.WriteLine(tree);
            // generate compiled object with references to commonly used .NET Framework assemblies
            var compilation = CSharpCompilation.Create("CSharp2Json",
                new SyntaxTree[] { tree },

                references: new[]
                {
                    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),      // mscorelib.dll
                    MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),  // System.Core.dll
                    MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),         // System.dll
                    MetadataReference.CreateFromFile(typeof(DataSet).Assembly.Location),     // System.Data.dll
 //                   MetadataReference.CreateFromFile(typeof(EntityKey).Assembly.Location),   // System.Data.Entity.dll
                    MetadataReference.CreateFromFile(typeof(XmlDocument).Assembly.Location), // System.Xml.dll

                },
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
            );
            System.Console.WriteLine(compilation);
            // load compiled bits into assembly
            Assembly assembly;
            using (var memoryStream = new MemoryStream())
            {
                var result = compilation.Emit(memoryStream);

          /*      if (!result.Success)
                {
                    throw new System.ArgumentException("Parameter cannot be null", "original");

                }
                */
                    assembly = AppDomain.CurrentDomain.Load(memoryStream.ToArray());

            }

            // instantiate object instances from assembly types
            foreach (var definedType in assembly.DefinedTypes)
            {
                Type objType = assembly.GetType(definedType.FullName);
                if (objType.BaseType?.FullName != "System.Enum")
                {
                    object instance = null;
                    try
                    {
                        instance = assembly.CreateInstance(definedType.FullName);
                    }
                    catch (MissingMethodException)
                    {
                        // no default constructor - eat the exception
                    }

                    if (instance != null)
                    {
                        yield return instance;
                    }
                }
            }
        }
    }
}

//错误日志:

未处理的异常:System.BadImageFormatException:无法加载从RoslynCompileSample,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'或其依赖项之一加载的文件或程序集'0字节。尝试加载格式不正确的程序。 ---> System.BadImageFormatException:错误的IL格式。 ---内部异常堆栈跟踪的结束---在System.Reflection.RuntimeAssembly.nLoadImage(Byte [] rawAssembly,Byte [] rawSymbolStore,Evidence evidence,StackCrawlMark&stackMark,Boolean fIntrospection,Boolean fSkipInteg rityCheck,SecurityContextSource securityContextSource)at System。位于C:\ Users \ RoboMQ-sagarrana \ Desktop \ graphql \ RoslynCompileSample \ RoslynCompileSample \ Program.cs中的RoslynCompileSample.Program.d__0.MoveNext()的AppDomain.Load(Byte [] rawAssembly):RoslynCompileSample.Program.Main的第100行( String [] args)在C:\ Users \ RoboMQ-sagarrana \ Desktop \ graphql \ RoslynCompileSample \ RoslynCompileSample \ Program.cs:第141行

c# asp.net .net asp.net-core roslyn
1个回答
0
投票

看一下代码,它听起来像你试图加载的可执行文件是64位,你试图将它加载到32位应用程序(或可能反过来)。

© www.soinside.com 2019 - 2024. All rights reserved.