Expressingx
Expressingx

Reputation: 1572

Predefined type 'System.Object' is not defined or imported

I have console application which should support scripts (.cs files) in order to change the behavior of the application. The problem is that I have 9 errors of type 'Predefined type is not defined or imported'

enter image description here

I've searched a lot and couldn't fix the issue, my code is

public static void LoadAndRunScript(string fileName, IModbusSlaveNetwork network)
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "scripts", fileName);
        using (var streamReader = File.OpenRead(path))
        {
            string generatedAssemblyName = Path.GetRandomFileName();
            var refs = new List<MetadataReference>();

            foreach (var referencedAssembly in Assembly.GetEntryAssembly().GetReferencedAssemblies())
            {
                var loadedAssembly = Assembly.Load(referencedAssembly);

                refs.Add(MetadataReference.CreateFromFile(loadedAssembly.Location));
            }


            var compilation = CSharpCompilation.Create(generatedAssemblyName)
                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddReferences(refs)
                .AddSyntaxTrees(CSharpSyntaxTree.ParseText(SourceText.From(streamReader), path: path));

            var ms = new MemoryStream();

            var result = compilation.Emit(ms);
            if (result.Success)
            {
                // yay
            }

            var assembly = LoadAssembly(ms, ms);

            assembly.GetType().GetMethod("Start").Invoke(null, new object[] { network });
        }
    }

    private static Assembly LoadAssembly(MemoryStream peStream, MemoryStream pdbStream)
    {
        return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(peStream, pdbStream);
    }

Upvotes: 2

Views: 489

Answers (0)

Related Questions