Posting Image directly in Twitter using Status with Media in C#

I got this task. And after searching a lot, i acheived this.

I was using TweetSharp api in my application.So i tried to achieve with that.
It gives you solution so that you can achieve that by Twitpic Api.

Then I read POST statuses/update_with_media

Tried a lot, not able to do with the C# twitter api’s too like TweetSharp, Hommock etc..
Then Here is the solution 🙂

Step 1: Make Oauth Authorization Header

Simple, Download OAuth.Manager dll from here

Add Reference in your project. And add namespace (Using OAuth;) in your page.

Note : I am assuming here you have made the request to the user before and have configuration key, configuration secret, access token and access secret. You can do it by any C# api.

Step 2: Using this dll and generating header

Setting request Values :

var oauth = new OAuth.Manager();
oauth["consumer_key"] = ~Your application's Key~;
oauth["consumer_secret"] = ~Your application's Secret~;
oauth["token"] = ~Access token~;
oauth["token_secret"] = ~Access secret~;

Making Request :

var url = "";
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
var request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);

Step 3: Adding image to OAuth request and Posting

Here is the message to be uploaded sent as status
string message = "Hello Image Demo";

Here is the image
string imageFile = HttpContext.Current.Server.MapPath("/Images/abc.png"); //Sample image

if (imageFile != null)
string boundary = “~~~~~~” +
Guid.NewGuid().ToString().Substring(18).Replace(“-“, “”) +

var separator = “–” + boundary;
var footer = “\r\n” + separator + “–\r\n”;
string shortFileName = Path.GetFileName(imageFile);
string fileContentType = “image/png”;
string fileHeader = string.Format(“Content-Disposition: file; ” +
“name=\”media\”; filename=\”{0}\””,
var encoding = System.Text.Encoding.GetEncoding(“iso-8859-1”);

var contents = new System.Text.StringBuilder();
contents.AppendLine(“Content-Disposition: form-data; name=\”status\””);
contents.AppendLine(string.Format(“Content-Type: {0}”, fileContentType));

// actually send the request
request.ServicePoint.Expect100Continue = false;
request.ContentType = “multipart/form-data; boundary=” + boundary;

using (var s = request.GetRequestStream())
byte[] bytes = encoding.GetBytes(contents.ToString());
s.Write(bytes, 0, bytes.Length);
bytes = File.ReadAllBytes(imageFile);
s.Write(bytes, 0, bytes.Length);
bytes = encoding.GetBytes(footer);
s.Write(bytes, 0, bytes.Length);

Now Request Made Getting response

using (var response = (HttpWebResponse)request.GetResponse())
if (response.StatusCode == HttpStatusCode.OK)
//Posting Successfull

All Done. Image Posted Successfully 🙂