1

I want to send data and a file using WebRequest.

byte[] fileStream = File.ReadAllBytes(path);

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });

WebRequest request = WebRequest.Create(url);

request.ContentType = "application/json";
request.Method = "POST";
request.Credentials = new NetworkCredential("name", "pw");

Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
//dataStream.Write(fileStream, 0, fileStream.Length);

dataStream.Write(fileStream, 0, fileStream.Length); //CAUSES A CRASH
dataStream.Close();
WebResponse response = request.GetResponse();

I don't know why it fails, if I include the "dataStream.Write(fileStream, 0, fileStream.Length);" line the server fails to accept my stream, saying there was an internal error. I have an working CURL command showing me the data the Server wants.

curl -k -X POST -u name:pw -H "Content-type: application/json"
-H 'Accept:application/json''url'
-d'{parameters}'
--data-binary @file.wav

In case I exclude the mentioned line, the command works as expected, telling me that there was no input file. So I think there might be something wrong about the file.wav

1 Answer 1

1

That code will write some JSON-formatted data, immediately followed by the raw bytes of file.wav. That is most likely not what the receiving server is expecting. Typically if you want to send a file and data at the same time you would use a MIME multipart encoding. It is possible that curl is doing that for you automatically. It would be good to confirm that hypothesis by hooking up a debugging proxy such as Fiddler, and watching what curl is actually sending. Then try to emulate that in C#.

If you do need to send a multipart messages, then it would be helpful to know which version of the .NET framework you are using. There are easier ways to do it in some of the newer versions.

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

2 Comments

Hi, since I never did anything like that, I don't know what to look for. I have captured the communication using Wireshark because the win32 versions of curl have a problem with this server. What do I need to look for to prove the hypothesis? I'm using .NET 4.5
The idea is to compare your working example (curl) to the broken example (C#). The differences between them should point you at areas for further investigation. If you edit your question with the two captures I could try to take a look at it. No need to include all data for uploaded file, just the HTTP headers and the beginning of the request body would be enough.

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.