Home > Uncategorized > Get a profile ID from Facebook URL in C#

Get a profile ID from Facebook URL in C#

If you want to convert a Facebook URL like http://www.facebook.com/LambOfficial into a profile id, “56062886901”, so that you can link to the page using the FB:// protocol, i.e. FB://profile/56062886901 – which looks better than a web link on iOS. Then the simple trick is to replace the “www” with “graph”, and then look for the id parameter.

To do this from code, then you would use something like this:

const string strFBRegex = @”id.:..(?<id>\d+).,”;
var strGraphUrl = strUrl.Replace(“www”, “graph”);
var wc = new System.Net.WebClient();
var strGraphJson = wc.DownloadString(strGraphUrl);
strId = System.Text.RegularExpressions.Regex.Match(strGraphJson, strFBRegex).Groups[“id”].Value;

Where strUrl is the input url, and strID is the output.

However, this does not account for facebook pages that have the format http://www.facebook.com/pages/pagename/id, in which the profile id is visible in the url, but the graph page does not work.

So, something like this catches this case also:

var strId = “”;
if (!strUrl.ToLower().Contains(“/pages/”))
{
const string strFBRegex = @”id.:..(?<id>\d+).,”;
var strGraphUrl = strUrl.Replace(“www”, “graph”);
var wc = new System.Net.WebClient();
var strGraphJson = wc.DownloadString(strGraphUrl);
strId = System.Text.RegularExpressions.Regex.Match(strGraphJson, strFBRegex).Groups[“id”].Value;
}
else
{
strId = System.Text.RegularExpressions.Regex.Match(strUrl, @”\d+”).Value;
}
strFBUrl = “fb://profile/” + strId;

 

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: