38
1
using System;
2
using System.Diagnostics;
3
using System.IO;
4
using System.CodeDom;
5
using System.CodeDom.Compiler;
6
7
//http://metadataconsulting.blogspot.com/2020/11/CSharp-dotNet-How-to-to-get-the-literal-dotNet-string-the-internal-storage-representation-of-a-CSharp-string.html
8
9
public static class Program
10
{
11
public static string ToLiteral(this string input)
12
{
13
using (var writer = new StringWriter())
14
{
15
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
16
{
17
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
18
19
return writer.ToString();
20
}
21
}
22
}
23
24
public static void Main()
25
{
26
Stopwatch sw = new Stopwatch();
27
28
string emptytest = "1 \0 \0 \u0001 \0 \0\r\n\tSOS\n1 0 0 1 0 0 1\r\nIn distress\r\n1 0 0 1 0 0 1\r\nUnicode \\u0081 on the next line\n\n\u0081";
29
sw.Start();
30
string output = emptytest.ToLiteral();
31
sw.Stop();
32
33
Console.WriteLine(emptytest);
34
Console.WriteLine("---- Literal -----");
35
Console.WriteLine(output + " in " + sw.ElapsedTicks + " ticks");
36
37
}
38
}
Cached Result