Media upload using media/upload endpoint of twitter using c# not working. Everytime geting a 401 Unauthorised Error

csharp
oauth

#1

Hi All,

Can any one please help here. I am struggling since last 4 weeks to get media upload working. I am getting 401 Unauthorized Error. I am running out of options now. Please help. I am posting my entire c# code here. Please let me know what is the actual issue here. I have also gone through the guide to upload media documentation, there it says to remove POST from the base string, also did that but still no luck.

 public void SendStatusWithMedia()
        {            
            var file = @"C:\Users\admin.XXX\Desktop\FreeElectricity.png";
            byte[] imageData = File.ReadAllBytes(file);
            int totalbytes = imageData.Length;
            Encoding EncodingAlgorithm = Encoding.GetEncoding("iso-8859-1");
            string Boundary = DateTime.Now.Ticks.ToString("x");
            string StartBoundary = string.Format("--{0}\r\n", Boundary);
            string EndBoundary = string.Format("\r\n--{0}\r\n", Boundary);
            string sContentType = "multipart/form-data;boundary=" + Boundary;
            string contentDisposition = "Content-Disposition: form-data; ";
            string contenName = "name=\"Media\";\r\n ";            
            string Data = EncodingAlgorithm.GetString(imageData, 0, imageData.Length);
            var contents = new System.Text.StringBuilder();
            contents.Append(String.Format("{0}{1}{2}{3}{4}", StartBoundary, contentDisposition, contenName, sContentType, Data));
            contents.Append(EndBoundary);
           
            byte[] Content = EncodingAlgorithm.GetBytes(contents.ToString());

            

            string oauth_consumer_key = "XXXXXXXXXXXXXXX";
            string oauth_consumerSecret = "XXXXXXXXXXXXXXXX";
            string oauth_signature_method = "HMAC-SHA1";
            string oauth_version = "1.0";
            string oauth_token = "XXXXXXXXXXXXXXXXXXXXX";
            string oauth_token_secret = "XXXXXXXXXXXXXXXXXXX";
            
            string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
            TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
            string url =string.Format("https://upload.twitter.com/1.1/media/upload.json");
            SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>();

            
            basestringParameters.Add("oauth_version", oauth_version);
            basestringParameters.Add("oauth_consumer_key", oauth_consumer_key);
            basestringParameters.Add("oauth_nonce", oauth_nonce);
            basestringParameters.Add("oauth_signature_method", oauth_signature_method);
            basestringParameters.Add("oauth_timestamp", oauth_timestamp);
            basestringParameters.Add("oauth_token", oauth_token);
            basestringParameters.Add("oauth_token_secret", oauth_token_secret);


            //Build the signature string
            StringBuilder baseString = new StringBuilder();
            baseString.Append("POST" + "&");            
            baseString.Append(EncodeCharacters(Uri.EscapeDataString(url + "&")));
            foreach (KeyValuePair<string, string> entry in basestringParameters)
            {
                baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&")));
            }

            //GS - Remove the trailing ambersand char, remember 
            //it's been urlEncoded so you have to remove the 
            //last 3 chars - %26
            string finalBaseString = baseString.ToString().Substring(0, baseString.Length - 3);

            //Build the signing key    
            string signingKey = EncodeCharacters(Uri.EscapeDataString(oauth_consumerSecret)) + "&" +
            EncodeCharacters(Uri.EscapeDataString(oauth_token_secret));

            //Sign the request
            HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey));
            string signatureString = Convert.ToBase64String(hasher.ComputeHash(new ASCIIEncoding().GetBytes(finalBaseString)));

            //Tell Twitter we don't do the 100 continue thing
            ServicePointManager.Expect100Continue = false;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url);

            


            StringBuilder authorizationHeaderParams = new StringBuilder();
            authorizationHeaderParams.Append("OAuth ");
            authorizationHeaderParams.Append("oauth_nonce=" + "\"" + Uri.EscapeDataString(oauth_nonce) + "\",");
            authorizationHeaderParams.Append("oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauth_signature_method) + "\",");
            authorizationHeaderParams.Append("oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauth_timestamp) + "\",");
            authorizationHeaderParams.Append("oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauth_consumer_key) + "\",");           
            authorizationHeaderParams.Append("oauth_token=" + "\"" + Uri.EscapeDataString(oauth_token) + "\",");
            authorizationHeaderParams.Append("oauth_token_secret=" + "\"" + Uri.EscapeDataString(oauth_token_secret) + "\",");            
            authorizationHeaderParams.Append("oauth_signature=" + "\"" + Uri.EscapeDataString(signatureString) + "\",");
            authorizationHeaderParams.Append("oauth_version=" + "\"" + Uri.EscapeDataString(oauth_version) + "\"");
            webRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString());

            webRequest.Method = "POST";
           
            webRequest.ContentType = sContentType;
            webRequest.ContentLength = Content.Length;
            
            Stream requestStream = webRequest.GetRequestStream();
            requestStream.Write(Content, 0, Content.Length);
            requestStream.Close();
            //Allow us a reasonable timeout in case Twitter's busy
            webRequest.Timeout = 3 * 60 * 1000;
            try
            {
                // webRequest.Proxy = new WebProxy("enter proxy details/address");
                HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
                Stream dataStream = webResponse.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
            }
            catch (Exception ex)
            {

            }
        }

private string EncodeCharacters(string data)
        {
            //as per OAuth Core 1.0 Characters in the unreserved character set MUST NOT be encoded
            //unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
            if (data.Contains("!"))
                data = data.Replace("!", "%21");
            if (data.Contains("'"))
                data = data.Replace("'", "%27");
            if (data.Contains("("))
                data = data.Replace("(", "%28");
            if (data.Contains(")"))
                data = data.Replace(")", "%29");
            if (data.Contains("*"))
                data = data.Replace("*", "%2A");
            if (data.Contains(","))
                data = data.Replace(",", "%2C");

            return data;
        }