【问题标题】:Unhandled Exception: System.BadImageFormatException: Could not load file or assembly '0 bytes loaded from RoslynCompileSample,未处理的异常:System.BadImageFormatException:无法加载从 RoslynCompileSample 加载的文件或程序集 '0 字节,
【发布时间】:2019-02-20 15:56:55
【问题描述】:

我正在尝试使用 Roslyn 编译器创建类的实例。但它抛出了上面的错误:代码是:

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=null' 或其依赖项之一。试图加载格式不正确的程序。 ---> System.BadImageFormatException: 错误的 IL 格式。 --- 内部异常堆栈跟踪结束 --- 在 System.Reflection.RuntimeAssembly.nLoadImage(Byte[] rawAssembly, Byte[] rawSymbolStore, 证据证据, StackCrawlMark& stackMark、布尔 fIntrospection、布尔 fSkipInteg rityCheck、SecurityContextSource securityContextSource) 在 System.AppDomain.Load(字节 [] 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

【问题讨论】:

  • 我相信您可以在没有大部分代码的情况下演示这一点(因此我们可以轻松重现)
  • 我在这一行中遇到错误 assembly = AppDomain.CurrentDomain.Load(memoryStream.ToArray());
  • ToArray() 真的会产生什么吗?这将是一个很好的起点
  • 我认为代码没有到达那一行对不起:
  • 编译.Emit(memoryStream);我不确定它是否给出错误,但这是 32 64 位问题吗

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


【解决方案1】:

看一眼代码,听起来您尝试加载的可执行文件是 64 位的,而您正尝试将其加载到 32 位应用程序中(或者可能反过来)。

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 2022-09-30
    • 2019-02-11
    • 2013-01-17
    • 1970-01-01
    • 2011-07-10
    • 2022-11-11
    • 2012-03-14
    相关资源
    最近更新 更多