2013-03-18 38 views
0

我正在使用Roslyn在运行时执行C#代码。使用Roslyn从外部文件执行代码

首先我想这个代码(正常工作):

engine.Execute(@"System.Console.WriteLine(""Hello World"");"); 

在那之后,我想从一个文本文件中执行代码,所以我这样做:

string line; 

System.IO.StreamReader file = new System.IO.StreamReader("test.txt"); 
while ((line = file.ReadLine()) != null) 
{ 
    engine.Execute(line); 
} 

我复制我之前在一个名为test.txt的外部文件中使用过的字符串。

所以我的test.txt包含以下行:@"System.Console.Write(""Hello World"");"

当compliling代码我得到一个错误少了东西。

所以我想通了,它只是反斜杠。

,并改变了代码如下:

string line; 

System.IO.StreamReader file = new System.IO.StreamReader("test.txt"); 
while ((line = file.ReadLine()) != null) 
{ 
    string toto = line; 
    string titi = toto.Replace(@"\\", @""); 

    engine.Execute(toto); 
} 

现在,当我运行此代码,没有任何反应(没有错误)。

当我检查变量的内容,我得到这个:

toto : "@\"System.Console.Write(\"\"Hello World\"\");\""

titi : "@\"System.Console.Write(\"\"Hello World\"\");\""

这是正常的!通常情况下,应该删除斜杠,但情况并非如此。

什么问题

EDIT

我要保持我过时了以罗斯林代码完全匹配的字符串,所以不建议样改变答案文件中的字符串。另请解决!

+0

试着把这段代码放在文件中:'System.Console.Write(“Hello World”);',没有别的。应该工作正常。 – 2013-03-18 16:26:23

+0

你是什么意思?我从来没有听说过! – 2013-03-18 16:26:53

+0

您不需要在文件中转义字符串。 StreamReader为您做到了这一点。只需输入它就像我编辑的评论。 – 2013-03-18 16:27:45

回答

7

您误解字符串。

@"..."字符串文字;它会创建一个值为...的字符串。

因此,当你写Execute(@"System.Console.WriteLine(""Hello World"");"),你传递给Execute()实际值System.Console.WriteLine("Hello World");

当你从文件中读取一个字符串,你得到的字符串的实际价值。
StreamReader不假定该文件包含C#字符串文字表达式(这将是非常奇怪的,意外的和无用的)。

因此,当您读取包含文本@"System.Console.WriteLine(""Hello World"");"的文件时,会得到一个实际值为@"System.Console.WriteLine(""Hello World"");"的字符串。
(写这一个字符串,你需要写@"@""System.Console.WriteLine(""""Hello World"""");""""

然后,当您传递字符串罗斯林的Execute()方法,罗斯林评估字符串常量表达式,并返回文本的字符串值。