How to solve “End of string expected at position 43.”

I was recently working on an Export module and had to deal with the following exception:

End of string expected at position 43.

This module was supposed to retrieve all child items of an specific item as you can see on the image below:




After debugging I managed I identified that his specific piece of code was throwing the exception:

var allmediaItems = masterDB.SelectItems(mediaFolder + "//*");

What was wrong?

Observe that the path passed on the TextBox contains a DASH.

The SelectItems function receives a Sitecore query as a parameter. This query needs to be able to escape dashes as it is an illegal character or it will through the exception above.

In order to fix this we need to insert # around the  part of the path containing the ‘-‘ sign.

In this specific case, the solution would be /sitecore/media library/GlobalChampions/#PDF-Files#.

So we need a function able to identify when there is a DASH in the query and then insert the HASH around this specific part of the path.

Rather than spending time building my own function I managed to find the following blog with the function ready to use:

private string EscapeItemNamesWithDashes(string queryPath)
            if (!queryPath.Contains("-"))
                return queryPath;

            var strArray = queryPath.Split(new char[] { '/' });
            for (int i = 0; i < strArray.Length; i++)
                if (strArray[i].IndexOf('-') > 0)
                    strArray[i] = "#" + strArray[i] + "#";
            return string.Join("/", strArray);

My final solution ended up being like the following:

var allmediaItems = masterDB.SelectItems(EscapeItemNamesWithDashes(mediaFolder) + "//*");

If that was of some help to you please share it to others!

Thanks for reading

Leave a Comment

%d bloggers like this: