In this article I will share a function I wrote that posts a picture to a user’s Wall/Timeline or one of his pages wall using the Facebook C# SDK.
The parameters needed are the picture’s full disk path, a description/caption to post along with the image and the Facebook user access token if you are posting to the user wall or the page access token if you are posting to one of his Facebook pages (there’s a difference between page access token and a user access token).
This function uses FQL to search the Album “Wall Pictures” Object ID, if the album is not found the function will exit.
private bool Post_Picture(string Picture_Path, string Picture_Caption, string AT, bool Is_User_Wall)
{
// new FacebookClient instance (AT: user access token or page access token)
var fb = new FacebookClient(AT);
string AlbumID = "";
if (!Is_User_Wall)
{
// Find the 'Wall Photos' Album Object_ID
// alter this part to publish photos to a different album
var query = string.Format("SELECT object_id,name FROM album WHERE owner = me()");
dynamic r1 = fb.Get("fql", new { q = query });
foreach (var post in r1.data)
{
if (post.name == "Wall Photos") { AlbumID = Convert.ToString(post.object_id); }
}
if (AlbumID == "") { MessageBox.Show("the album 'Wall Photos' not found."); return false; }
}
dynamic parameters = new ExpandoObject();
parameters.message = Picture_Caption;
parameters.source = new FacebookMediaObject
{
ContentType = "image/jpeg",
FileName = Path.GetFileName(Picture_Path)
}.SetValue(File.ReadAllBytes(Picture_Path));
try
{
if (Is_User_Wall)
{
// Post the image/picture to User wall
fb.Post("me/photos", parameters);
}
else
{
// Post the image/picture to the Page's Wall Photo album
fb.Post("/" + AlbumID + "/photos", parameters);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
This function will return true if the picture is posted successfully.
Have fun and don't hesitate to comment or ask questions.
Chtiwi Malek on Google+About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.