Tuesday, 11 December 2012

0x1F, 0x1F, wherefore art thou 0x1F?

Playing with XML in .net you might run into some pesky characters that throw errors during conversions. One offender is 0x1F which can be hard to remove. Replacing the character can lead to surprising issues, check the variables below and their values:

// string x contains the bad char.
var a = x.IndexOf('\u001f');                     // 513
var b = x.IndexOf(Convert.ToString((byte)0x1F)); // -1
var c = x.Contains(Convert.ToChar((byte)0x1F));  // true
var d = x.Contains('\u001f');                    // true
var e = x.Contains(Convert.ToString((byte)0x1F));// false
var f = x.Contains(Convert.ToChar((byte)0x1F));  // true

If you simply want to remove the character:

x = x.Replace(Convert.ToChar((byte)0x1F), ' '); // Works
x = x.Replace(Convert.ToString((byte)0x1F), "");// Fails

  • http://stackoverflow.com/questions/9949921/
  • http://stackoverflow.com/questions/6728329/

No comments:

Post a Comment