Th3Wolf
Th3Wolf

Reputation: 149

C# executing a code in string gives errors always

I'm trying to make a command system like each command has an action as string like that :

     CommandReader.commands.Add(new CommandReader("MESSAGE", @"
        using System;

        namespace HelloWorld
        {
/// <summary>
/// Summary description for Class1.
/// </summary>
class HelloWorldClass
{
            static void Main(string[] args)
            {
                Console.WriteLine("+"Hello World!"+@");
                Console.ReadLine();
            }
 }
   }

        "));

and to read the code I used this method:

      public static bool ExecuteCommand(string action)
    {
        try
        {
            CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

            ICodeCompiler codeCompiler = codeProvider.CreateCompiler();
            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.GenerateExecutable = true;
            compilerParams.OutputAssembly = "Sys.exe";



            CompilerResults compilerRes = codeCompiler.CompileAssemblyFromSource(compilerParams, action);
            Process.Start("Sys.exe");
            if (compilerRes.Errors.Count > 0) throw new Exception();



            return true;
        }catch(Exception)
        {
            MessageBox.Show("Virus error compiling code");
        }
        return false;
    }

i'm always getting errors in the CompilerResults can anyone tell me what is wrong with my code

Upvotes: 0

Views: 96

Answers (2)

Icarus
Icarus

Reputation: 63970

Your source code doesn't compile due to the incorrect way you are concatenating the strings. It should be like so:

string action = @"
using System;

    namespace HelloWorld
    {

        class HelloWorldClass
        {
              static void Main(string[] args)
              {
                   //pay attention to the @ next to hello world
                   Console.WriteLine(""" + @"Hello World!""" + @");
                   Console.ReadLine();
              }
        }
     }
";

Upvotes: 0

Emmanuel N
Emmanuel N

Reputation: 7449

Replace Console.WriteLine("+"Hello World!"+@"); with Console.WriteLine(""Hello World!"");. "" escapes "

Upvotes: 2

Related Questions