dotNETLiteralString

CSharp · Console

/Program.cs

using System;
using System.Diagnostics;
using System.IO; 
using System.CodeDom;
using System.CodeDom.Compiler; 
		
//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

public static class Program
{
	public static string ToLiteral(this string input)
	{
		using (var writer = new StringWriter())
		{
			using (var provider = CodeDomProvider.CreateProvider("CSharp"))
			{
				provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);

				return writer.ToString();
			}
		}
	}

	public static void Main()
	{
		 Stopwatch sw = new Stopwatch();

            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";
            sw.Start();
            string output = emptytest.ToLiteral(); 
            sw.Stop();
		
        Console.WriteLine(emptytest);    
		Console.WriteLine("---- Literal -----");    
		Console.WriteLine(output + " in " + sw.ElapsedTicks + " ticks");

	}
}
;