I am using below code to send a byte array to a site. Why this code is not throwing an exception even when there is no internet connection?.Even when no connection is there I am able to get stream and able to write to it.I expect it to throw an exception at Stream postStream = request1.EndGetRequestStream(result).Anyone got any idea why its behaving like this.
private void UploadHttpFile()
{
HttpWebRequest request = WebRequest.CreateHttp(new Uri(myUrl));
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
request.UserAgent = "Mozilla/4.0 (Windows; U; Windows Vista;)";
request.Method = "POST";
request.UseDefaultCredentials = true;
request.BeginGetRequestStream(GetStream, request);
}
private void GetStream(IAsyncResult result)
{
try
{
HttpWebRequest request1 = (HttpWebRequest)result.AsyncState;
using (Stream postStream = request1.EndGetRequestStream(result))
{
int len = postBody.Length;
len += mainBody.Length;
len += endBody.Length;
byte[] postArray = new byte[len + 1];
Encoding.UTF8.GetBytes(postBody.ToString()).CopyTo(postArray, 0);
Encoding.UTF8.GetBytes(mainBody).CopyTo(postArray, postBody.Length);
Encoding.UTF8.GetBytes(endBody).CopyTo(postArray, postBody.Length + mainBody.Length);
postStream.Write(postArray, 0, postArray.Length);
}
}
I expect it’s buffering everything until you’re done writing, at which point it will be able to use the content length immediately. If you set:
then I suspect it will fail at least when you write to the stream.
Btw, your calculation of the required length for
postArrayappears to be assuming one byte per character, which won’t always be the case… and you’re callingToStringonpostBodywhich looks like it’s redundant. I’m not sure why you’re trying to write in a single call anyway… either you could call Write three times:or (preferrably) just use a
StreamWriter:It’s also unclear why you’ve added 1 to the required length when initializing
postArray. Are you trying to send an extra “0” byte at the end of the data?