Can I convert a C# string value to an escaped string literal

后端 未结 16 837
时光取名叫无心
时光取名叫无心 2020-11-22 07:51

In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.

If

16条回答
  •  逝去的感伤
    2020-11-22 07:56

    If JSON conventions are enough for the unescaped strings you want to get escaped and you already use Newtonsoft.Jsonin your project (it has a pretty large overhead) you may use this package like the following:

    using System;
    using Newtonsoft.Json;
    
    public class Program
    {
        public static void Main()
        {
        Console.WriteLine(ToLiteral( @"abc\n123") );
        }
    
        private static string ToLiteral(string input){
            return JsonConvert.DeserializeObject("\"" + input + "\"");
        }
    }
    

提交回复
热议问题