private void ExecuteOffThread() { var client = (new FourSquareWebClient()).GetWrappedClientTemporary(); var newUri = FourSquareWebClient.CreateServiceRequest(Uri, UseCredentials); //client.DownloadStringCompleted += DownloadStringCompleted; // 1. Try posting string. // 2. Try multipart post. // 3. Regular get request. if (PostString != null) { client.UploadStringCompleted += client_UploadStringCompleted; client.UploadStringAsync(newUri, PostString); //client.DownloadStringAsyncWithPost(r, PostString); } else if (PostBytes != null && PostBytes.Length > 0) { // TODO: PHOTO UPLOAD: Add aprams for NAME (photo) and FILENAME string uploadFilename = "image.jpg"; string boundary = Guid.NewGuid().ToString(); string mpt = "multipart/form-data; boundary=" + boundary; var ms = new MemoryStream(); byte[] headerBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] footerBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); string keyValueFormat = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; if (PostParameters != null) { foreach (string key in PostParameters.Keys) { string formitem = string.Format( CultureInfo.InvariantCulture, keyValueFormat, key, PostParameters[key]); byte[] formitembytes = Encoding.UTF8.GetBytes(formitem); ms.Write(formitembytes, 0, formitembytes.Length); } } ms.Write(headerBytes, 0, headerBytes.Length); string hdt = string.Format( CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n", "photo", uploadFilename); byte[] hb = Encoding.UTF8.GetBytes(hdt); ms.Write(hb, 0, hb.Length); ms.Write(PostBytes, 0, PostBytes.Length); // this worked when i wrote only header bytes length! ms.Write(footerBytes, 0, footerBytes.Length); byte[] finalData = ms.ToArray(); ms.Close(); var legacyClient = new LegacyWebClient(); var r = legacyClient.CreateServiceRequest(Uri, UseCredentials); legacyClient.DownloadStringCompleted += OnLegacyClientDownloadStringCompleted; legacyClient.DownloadStringAsyncWithPost(r, finalData, mpt); } else { client.DownloadStringCompleted += DownloadStringCompleted; client.DownloadStringAsync(newUri); } }