Easily Sanitize a Sitecore Item Name in C#

Jan 23, 2012 by Mark Ursino    3 Comments    Posted under: Sitecore

Say you’re creating a new Sitecore item programmatically in C#. The general approach is to take some piece of data from your original data point, e.g. an article in a feed, and sanitize it so your item name is valid in Sitecore. Let’s take the example of an article’s title. Most developers will strip out the invalid character’s they can think would cause issues in Sitecore, e.g. !,.:; etc…

Here’s an easier way to do it with Sitecore’s own configuration:

char[] invalidcharacters = Sitecore.Configuration.Settings.InvalidItemNameChars;
string sanitizedName = string.Concat(possibleName.Trim().Split(invalidcharacters));

Notice Sitecore.Configuration.Settings.InvalidItemNameChars gives you a character array of the characters defined in the web.config. From there, we just trim whitespace away from the name, split the string at each “invalid” character and then concatenate the split chunks.

For re-usability, here it is as an overloaded extension method:

public static string SanitizeToItemName(this string possibleName)
{
  return SanitizeToItemName(possibleName, Sitecore.Configuration.Settings.InvalidItemNameChars);
}

public static string SanitizeToItemName(this string possibleName, char[] invalidCharacters)
{
  return string.Concat(possibleName.Trim().Split(invalidCharacters));
}

UPDATE:

Mark van Aalst identified that the Sitecore API has a utility method that does something like this already: Sitecore.Data.Items.ItemUtil.ProposeValidItemName(name, defaultValue);. Thanks for the tip Mark!

3 Comments + Add Comment

  • There is also a method called ProposeValidItemName within the Sitecore.Data.Items.ItemUtil class which does the same. It also has an overload for a default value.

    string itemName = ItemUtil.ProposeValidItemName(name, defaultValue);

  • Thanks Mark! Didn’t know that existed — definitely going to be using that much more.

  • [...] to leverage the work they’ve done to ensure proper item names as pointed out in the comments here. So above all else, if you are trying to ensure that code you write is using the same logic as [...]

Got anything to say? Go ahead and leave a comment!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>