Parsing FileRef with Regex

Custom List items in SharePoint lacks an "ego-link field". The closes is the FileRef field that contain values like:

1;#weblog/Lists/Blogmeddelelser/1_.000

You can mix the fields EncodedAbsUrl with parts of FileRef, add an aspx page name and actually get the real deal. This simple regular expression will match the ID and the list path relative to the site collection:

(?'id'\d+)(?:\;#)(?'path'.*?)\d+_.

The following code will help a long way.

readonly static Regex _fileRefParser = new Regex(  
    @"(?'id'\d+)(?:\;\#)(?'path'.*?)\d+_\.", 
    RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
static Uri GetUri(string encodedAbsUrl, string fileRef, bool isBlog)  
{
    Match match = _fileRefParser.Match(fileRef);
    return new Uri(
        string.Format(
            CultureInfo.InvariantCulture,
            "{0}{1}{2}.aspx?ID={3}",
            encodedAbsUrl,
            match.Groups["path"],
            isBlog ? "ViewPost" : "DispForm",
            match.Groups["id"]),
        UriKind.Absolute);
}
Google
m@kli.dk @klinkby RSS feed  GitHub