Search code examples
c#cmdcsc

csc.exe from C# code


I wan to compile C# code from another written in C#.

I have written following code so far:

string cscPath = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe";
string command = "/c \"" + cscPath + "\" /out:\"" + resultsFilePath 
+ "\" /reference:\"" + dllPath 
+ "\" \"" + csFilePath + "\" > \"" + resultsPath + "\\result.txt\"";

Process.Start("cmd.exe", command );

result.txt file is not created and I do not know how to check error message.

If I run something like this:

string command = "/c echo something > \"" + resultsPath + "\\result.txt\"";
Process.Start("cmd.exe", command);

it works and result.txt contains "something" word.

I work with Visual Studio 2012.


Solution

  • there is actually the possibility to compile C# code on the fly already built-in, so you don't need to go through the troubles of calling csc.exe yourself. Have a look at the following blog post which explains how to do it: https://blogs.msdn.microsoft.com/abhinaba/2006/02/09/c-writing-extendable-applications-using-on-the-fly-compilation/

    If you want to do it anyway with the via calling csc.exe, you could try calling csc.exe directly and not via the commandline:

    string cscPath = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe";
    var cscArguments = "...";
    Process.Start(cscPath, cscArguments);
    

    In order to find the error, you can run the exact same command from the commandline and check the output there. That should bring you on the right track.