I’m trying to convert a value retrieved from a deserialized XML file into a char.
<Delimiter>\t</Delimiter>
When I deserializing this XML into an object with a string property it becomes:
"\\t"
However, when I try to use the following code to get a char:
char c = Convert.ToChar(stringValue);
I get the exception:
System.FormatException: 'String must be exactly one character long.'
If execute this code, it works:
char c = Convert.ToChar("\t");
How to I convert my string "\\t" into "\t" in order to convert it to a char?
I tried str = str.Replace("\\\\", "\\") but that didn’t seem to get rid of the escape backslash.
>Solution :
The literal \t is interpretted by C# as a single tab (0x9) character before calling .ToChar().
Additionally, you are NOT getting \\t (three characters) as a result of deserializing that xml. You are getting (\t) (two characters), but the debugger is trying to be overly helpful and escaping the \ escape character.
So, how do you convert the two \ and t characters and get the final tab (0x9) character result?
You can use Regex.Unescape() for this.
See it work here: