Can I expand a string that contains C# literal expressions at runtime
If I have a string that contains a c# string literal expression can I "expand" it at runtime
public void TestEvaluateString()
{
string Dummy = EvalString( @"Contains \r\n new line");
Debug.Assert(Dummy == "Contains \r\n new line");
}
private string EvalString(string input)
{
return "Contains \r\n new line";
}
Like Can I convert a C# string value to an escaped string literal, but in reverse?
Solution 1:
Similar to Mikael answer but using the CSharpCodeProvider:
public static string ParseString(string txt)
{
var provider = new Microsoft.CSharp.CSharpCodeProvider();
var prms = new System.CodeDom.Compiler.CompilerParameters();
prms.GenerateExecutable = false;
prms.GenerateInMemory = true;
var results = provider.CompileAssemblyFromSource(prms, @"
namespace tmp
{
public class tmpClass
{
public static string GetValue()
{
return " + "\"" + txt + "\"" + @";
}
}
}");
System.Reflection.Assembly ass = results.CompiledAssembly;
var method = ass.GetType("tmp.tmpClass").GetMethod("GetValue");
return method.Invoke(null, null) as string;
}
You might be better off using a dictionary of wildcards and just replacing them in the string.
Solution 2:
Regex.Unescape
would be my method of choice.
Solution 3:
Not sure if this is the simplest way, but by referencing the Microsoft.JScript
namespace you can reparse it with the javascript eval
function.
Here's a test for the code at the bottom
var evalToString = Evaluator.MyStr("test \\r\\n test");
This will turn the \r into a carriage return.
And the implementation
public class Evaluator
{
public static object MyStr(string statement)
{
return _evaluatorType.InvokeMember(
"MyStr",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}
static Evaluator()
{
ICodeCompiler compiler;
compiler = new JScriptCodeProvider().CreateCompiler();
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator.Evaluator");
_evaluator = Activator.CreateInstance(_evaluatorType);
}
private static object _evaluator = null;
private static Type _evaluatorType = null;
private static readonly string _jscriptSource =
@"package Evaluator
{
class Evaluator
{
public function MyStr(expr : String) : String
{
var x;
eval(""x='""+expr+""';"");
return x;
}
}
}";
}