3

I am trying to convert a cURL script to a C# script. If I want to POST an image do I have to convert it to a string?

When I try running my script I get an exception from the target machine. Unfortunately I don't have access to see the code on the target machine.

$ch = curl_init();
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:"));
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($ch, CURLOPT_USERPWD, "user:pwd");
curl_setopt($ch, CURLOPT_URL, 'http://192.168.1.105/upload.php');
$data = array('type' => 'upload', 'student' => 'Peter', 'class' => '101', 'fotograf'          => 'Jane', 'file' => '@/pictures/image1.jpg');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);

This is what I have come up with:

WebRequest request = WebRequest.Create("http://192.168.1.105/upload.php");

request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("type=upload&student=Peter&calss=101&fotograf=Jane&file=/pictures/image1.jpg");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

WebResponse response = request.GetResponse();

Any ideas?

3
  • Could you bring the exact exception that you're getting? It should help with finding the exact problem. Commented Feb 23, 2012 at 21:01
  • I believe because your C# code is not doing the image upload as into the PhP code. in C# there no equivalent to @ like php, you must be write the boundary in headers, or to use some method like [UploadFile()][1] from WebClient class. [1]: msdn.microsoft.com/en-us/library/36s52zhs.aspx Commented Feb 23, 2012 at 21:10
  • The Exseption i get is: (417)exception failed Commented Feb 24, 2012 at 7:53

2 Answers 2

3

Possibly there is problem with the Authorization header and replacing:

string authInfo = "usr:pwd";
request.Headers["Authorization"] = "Basic " + authInfo;

with:

request.UseDefaultCredentials = false;
request.Credentials = new NetworkCredential(user, pwd);

might solve the problem.

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

1 Comment

Best answer, it should work both of Basic and Digest Authentication.
0

Before writing the buffer into the stream, make sure to convert it to a base64 string:

string result = System.Convert.ToBase64String(buffer);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.