I am new to this and what am i trying to do is POST a image as byte array to a URL, but i get error when i try to get the response.
Here is the code from MSDN:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(BASE_URL);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = fileContent; // my image as bytearray
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse(); // here it stops
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
While debugging in Stream, CanRead and CanSeek is false,Length and Position both throw same error:
'((System.Net.ConnectStream)dataStream).Length' threw an exception of type 'System.NotSupportedException'.
I tried copying to a memory stream, but same problem. Nothing that i found on internet helped me solve this.
In regards to debugging
This is normal behavior from a NetworkStream
The NetworkStream does not support random access to the network data stream. The value of the CanSeek property, which indicates whether the stream supports seeking, is always false; reading the Position property, reading the Length property, or calling the Seek method will throw a NotSupportedException.
In regards to your MSDN Example
The notes state
If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.
Although there are lots of ways to use WebRequest
It would be worth while wrapping this in a try catch
and working out what the actual exception is and what its telling you
try
{
WebResponse response = request.GetResponse();
...
...
}
catch(WebException ex)
{
// inspect Response and Status properties
}