System.CodeDom.Compiler showing error Compilation errors: The type or namespace name 'Collection' does not exist in the namespace 'System' (are you missing an assembl

beginer
beginer
1492 Points
51 Posts

I'm getting following error:

System.CodeDom.Compiler showing error 
Compilation errors: The type or namespace name 'Collection' does not exist in the namespace 'System' (are you missing an assembl

I'm trying to compile following code:

using System;
using System.Collection.Generic;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
           Stack<int> myStack = new Stack<int>();
           myStack.Push(1);
           myStack.Push(2);
           myStack.Push(3);
           myStack.Push(4);

          foreach (var item in myStack)
             Console.Write(item + ","); //prints 4,3,2,1,
        }
    }
}

Following are the source code in c#:

public CompilerResults CompileCode(string code)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            return provider.CompileAssemblyFromSource(parameters, code);
        }
Views: 237
Total Answered: 1
Total Marked As Answer: 0
Posted On: 09-Sep-2023 22:05

Share:   fb twitter linkedin
Answers
beginer
beginer
1492 Points
51 Posts
         

Resolved the issue by using regular expression as:

public CompilerResults CompileCode(string code)
        {
            Dictionary<string, string> packageAndAssemblies = new Dictionary<string, string>()
            {
                {"System","System" },
                {"System.Collections.Generic","mscorlib" }
            };
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            string pattern = @"using (@?[a-z_A-Z]\w+(?:\.@?[a-z_A-Z]\w+)*);";
            MatchCollection macthCollection = Regex.Matches(code, pattern, RegexOptions.IgnoreCase);
            foreach (Match match in macthCollection)
            {
                var packageName = match.Value.Replace("using ", "").Replace(";", "");
                packageAndAssemblies.TryGetValue(packageName, out var packageNameN);
                parameters.ReferencedAssemblies.Add($"{packageNameN ?? packageName}.dll");
            }
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            return provider.CompileAssemblyFromSource(parameters, code);
        }

Note: I did not found any way to get assembly name by package name in using block.

 

Posted On: 11-Sep-2023 02:41
 Log In to Chat