0

For example:

I have to post data according to this reference They ask to post a request with a local file as the body.

The curl they suggest is: curl -i --data-binary @test.mp3 http://developer.doreso.com/api/v1

But how can I do the same in c#?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
WananaBum
  • 57
  • 1
  • 3

1 Answers1

-1

Try using HttpWebRequest class and send file in a multipart/form-data request.

Here is a sample code that you may use with some modifications.

First read the contents of the file:

byte[] fileToSend = File.ReadAllBytes(@"C:\test.mp3"); 

Then prepare the HttpWebRequest object:

string url = "http://developer.doreso.com/api/v1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.ContentLength = fileToSend.Length;

Send the file as body request:

using (Stream requestStream = request.GetRequestStream())
{ 
    requestStream.Write(fileToSend, 0, fileToSend.Length);
    requestStream.Close();
}

Read the response then:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    result = reader.ReadToEnd();
}

Use the response if you need:

Console.WriteLine(result);
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
  • Do not [commit plagiarism](http://stackoverflow.com/questions/15087028/upload-multiple-files-in-a-single-httpwebrequest), especially when that code doesn't work (and yes, I saw you ninja-edit the similarities out). You also don't want to read the entire file in a byte array at once. – CodeCaster Feb 11 '15 at 16:49
  • 1
    a quick look at the docs says the Content-Type should be "application/octet-stream", not "multipart/form-data" – ry8806 Feb 11 '15 at 16:51