-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRoslynCompilation.cs
More file actions
83 lines (74 loc) · 3.06 KB
/
RoslynCompilation.cs
File metadata and controls
83 lines (74 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Code sample: dynamically compiling C# code using Roslyn API
//
//Copyright MSDN-WhiteKnight (https://github.com/MSDN-WhiteKnight), 2019
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace RoslynTest
{
class Program
{
static void RunScript()
{
var script = @"using System;
public static class Program
{
public static int Main(string[] args)
{
var x = 7 * 8;
Console.WriteLine(x.ToString());
return x;
}
}";
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
var refs = new List<PortableExecutableReference>
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")),
MetadataReference.CreateFromFile(Assembly.GetEntryAssembly().Location)
};
// Parse the script to a SyntaxTree
var syntaxTree = CSharpSyntaxTree.ParseText(script);
var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
// Compile the SyntaxTree to a CSharpCompilation
var compilation = CSharpCompilation.Create("Script",
new[] { syntaxTree },
refs,
new CSharpCompilationOptions(
OutputKind.ConsoleApplication,
optimizationLevel: OptimizationLevel.Release,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default)
);
var result = compilation.Emit("script.exe");
if (!result.Success)
{
throw new ApplicationException("Cannot compile script");
}
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "script.exe";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.UserName = "Vasya";
psi.Password = "123";
var process = new Process();
using (process)
{
process.StartInfo = psi;
process.Start();
while (!process.StandardOutput.EndOfStream)
{
string res = process.StandardOutput.ReadLine();
Console.WriteLine(res);
}
}
}
}
}