1

I am working on a c# project. I have to call an external web service and post file as binary data and read its response. Below is my code

var webClient = new WebClient();
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
var fileData = webClient.Encoding.GetString(file);
var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, filename, contentType, fileData);
var nfile = webClient.Encoding.GetBytes(package);
byte[] resp = webClient.UploadData(url, "POST", nfile);

I have passed content type as "application/octet-stream". I am surely missing something but cannot figure it out.

5
  • You'd be better off using HttpClient rather than WebClient. It'll handle the fiddly bits for you. Commented Jan 12, 2017 at 11:02
  • Have you tried simply WebClient.UploadFile? See MSDN Commented Jan 12, 2017 at 11:02
  • @Dillanm You are saying I donot need to specify content type in my code ? Commented Jan 12, 2017 at 11:04
  • 1
    @Dillanm Woah! that worked. Thanks Dilanm, sometimes we approach a task with complexity and forget that things can be simple. Thanks alot, you saved my day :) Commented Jan 12, 2017 at 11:07
  • @Neha No sorry; you'll still need to specify the content type but try using UploadFile in place of UploadData Commented Jan 12, 2017 at 11:08

1 Answer 1

1

Have you tried simply WebClient.UploadFile? See MSDN

(posted as answer for posterity)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.