C# is not supported when I compile the code using Microsoft-CodeAnalysis. I wonder why

若汝棋茗 41 Reputation points
2021-03-20T13:24:49.387+00:00

C# is not supported when I compile the code using Microsoft-CodeAnalysis. I wonder why

 List<MetadataReference> refs = new List<MetadataReference>();  
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();  
  
            foreach (var item in assemblies)  
            {  
                if (item.Location != null && item.Location != string.Empty)  
                {  
                    refs.Add(MetadataReference.CreateFromFile(item.Location));  
                }  
            }  
          
            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,  
                                usings: null,  
                                optimizationLevel: OptimizationLevel.Debug,  
                                checkOverflow: false,  
                                allowUnsafe: true,  
                                platform: Platform.AnyCpu,  
                                warningLevel: 4,  
                                xmlReferenceResolver: null);  
  
            var adhoc = new AdhocWorkspace();  
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);  
            adhoc.AddSolution(solutionInfo);  
  
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "RRQM", "RRQM", "C#")  
              .WithMetadataReferences(refs)  
              .WithCompilationOptions(compilationOptions);  
            adhoc.AddProject(projectInfo);  
  
              StringBuilder codeString = new StringBuilder();  
            codeString.AppendLine("using System.Reflection;");  
            codeString.AppendLine("using System.Runtime.CompilerServices;");  
            codeString.AppendLine("using System.Runtime.InteropServices;");  
            codeString.AppendLine("[assembly: ComVisible(false)]");  
            adhoc.AddDocument(projectInfo.Id, "AssemblyInfo.cs", SourceText.From(codeString.ToString()));  
            Project project = adhoc.CurrentSolution.GetProject(projectInfo.Id);  
            var compilation = project.GetCompilationAsync().Result;  
  
            using (MemoryStream dllStream = new MemoryStream())  
            using (Stream win32resStream = compilation.CreateDefaultWin32Resources(  
                                          versionResource: true, // Important!  
                                                                              noManifest: false,  
                                          manifestContents: null,  
                                          iconInIcoFormat: null))  
            {  
                EmitResult result = compilation.Emit(dllStream, win32Resources: win32resStream);  
                if (!result.Success)  
                {  
                    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>  
                       diagnostic.IsWarningAsError ||  
                       diagnostic.Severity == DiagnosticSeverity.Error);  
                    StringBuilder sboutputMessage = new StringBuilder();  
                    foreach (Diagnostic diagnostic in failures)  
                    {  
                        sboutputMessage.AppendFormat("\t{0}  {1}: {2}", diagnostic.Location.ToString(), diagnostic.Id, diagnostic.GetMessage() + Environment.NewLine);//调试的最终输出信息  
                    }  
                }  
                else  
                {  
                    
                }  
            }  

79739-qq%E6%88%AA%E5%9B%BE20210320212341.png

Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-03-22T09:33:38.163+00:00

    Try to add a nuget package: Microsoft.CodeAnalysis.CSharp.Workspaces

    After adding, the error disappeared.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. Ken Tucker 5,861 Reputation points
    2021-03-21T11:02:28.377+00:00

    Try replacing "C#" in the ProjectInfo.Create call with LanguageNames.CSharp

    https://learn.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.languagenames.csharp?view=roslyn-dotnet

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.