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

时间:2019-02-20 06:06:40

标签: c# asp.net .net asp.net-core roslyn

我正在尝试使用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加载的文件或程序集'0字节,   版本= 1.0.0.0,文化=中性,PublicKeyToken =空'       或其依赖项之一。试图加载格式错误的程序。 ---> System.BadImageFormatException:错误的IL   格式。          ---内部异常堆栈跟踪的结尾---          在System.Reflection.RuntimeAssembly.nLoadImage(Byte [] rawAssembly,Byte [] rawSymbolStore,证据,StackCrawlMark&   stackMark,布尔值fIntrospection,布尔值fSkipInteg       rityCheck,SecurityContextSource,securityContextSource)          在System.AppDomain.Load(Byte [] rawAssembly)          在RoslynCompileSample.Program.d__0.MoveNext()中   C:\ Users \ RoboMQ-sagarrana \ Desktop \ graphql \ RoslynCompileSample \ RoslynCompileSample \ Program.cs:line   100          在C:\ Users \ RoboMQ-sagarrana \ Desktop \ graphql \ RoslynCompileSample \ RoslynCompileSample \ Program.cs:line中的RoslynCompileSample.Program.Main(String [] args)   141

1 个答案:

答案 0 :(得分:0)

浏览一下代码,听起来好像您要加载的可执行文件是64位,而您正在尝试将其加载到32位应用程序中(或者可能相反)。