我正在使用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
我要保持我过时了以罗斯林代码完全匹配的字符串,所以不建议样改变答案文件中的字符串。另请解决!
试着把这段代码放在文件中:'System.Console.Write(“Hello World”);',没有别的。应该工作正常。 – 2013-03-18 16:26:23
你是什么意思?我从来没有听说过! – 2013-03-18 16:26:53
您不需要在文件中转义字符串。 StreamReader为您做到了这一点。只需输入它就像我编辑的评论。 – 2013-03-18 16:27:45