0

There are various methods in C# to escape strings, most deal with XML (SecurityElement.Escape) or JavaScript (HttpUtility.JavaScriptStringEncode).

Is there a standard .NET (.NET Standard 2.0) method to escape a string such that, when copied verbatim in a C# double-quoted literal, it will evaluate to original string?

Here is a sample desired transform of the string content from ff "Hello world!" ^M^M <>' to ff \"Hello world!\" \n\n <>' so that it can be copied verbatim into a valid program:

 var x = "ff \"Hello world!\" \n\n <>'";

Note that ^M (new line character) is transformed to the \n escape and <>' is left alone as angle brackets are irrelevant in context and the string will be double-quoted (escaping of ' would be OK).

Consider the VS Debugger expression view's rendition of string values for an example of desired output. Sometimes this might be referred to as 'string representation form'.

user2864740
  • 60,010
  • 15
  • 145
  • 220
  • Does this answer your question? [Convert a C# string value to an escaped string literal with Roslyn](https://stackoverflow.com/questions/55514123/convert-a-c-sharp-string-value-to-an-escaped-string-literal-with-roslyn) – GSerg Dec 11 '19 at 22:07
  • @GSerg Thanks, that's the output I'm looking for. Unfortunately it establishes a CodeDomProvider/Roslyn dependency which is a bit .. heavy. – user2864740 Dec 11 '19 at 22:08
  • Well, I guess the next best thing is to manually implement [this table](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-escape-sequences). – GSerg Dec 11 '19 at 22:15
  • Hmm. I suppose that "encode for a JSON string" might be sufficiently close. Also doesn't appear readily a thing. – user2864740 Dec 11 '19 at 22:16
  • Create a list of key/value pairs (or some other 2-tuple) that represent what you want to do. Then walk through the list calling `StringBuilder.Replace` for each pair doing the transformation. StringBuilder's Replace call is more appropriate than string's here. – Flydog57 Dec 12 '19 at 17:47

0 Answers0