Reputation: 3910
I'm trying to open a connection to a server and get the response body, which is an image. I want to save it to Image
, and later display it in the PictureBox
. Here is my code:
try
{
var response = WebRequest.Create(String.Format(url + "?t=webwx&_={0}", timestamp));
var stream = response.GetRequestStream();
Image image = Image.FromStream(stream);
qe_img.Image = image;
qe_img.Height = image.Height;
qe_img.Width = image.Width;
} catch (Exception e)
{
Console.WriteLine(e);
}
I get:
Exception thrown: 'System.Net.ProtocolViolationException' in System.dll
System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
at System.Net.HttpWebRequest.CheckProtocol(Boolean onRequestStream)
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at WindowsFormsApplication1.Form1.showQRImage() in c:\users\morgan\documents\visual studio 2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 70
But I always get a WebException
. I'm new to C#, I wonder what is wrong here. Thanks.
Upvotes: 0
Views: 468
Reputation: 28672
Try this
try
{
var request = WebRequest.Create(String.Format(url + "?t=webwx&_={0}", timestamp));
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
Image image = Image.FromStream(stream);
qe_img.Image = image;
qe_img.Height = image.Height;
qe_img.Width = image.Width;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Upvotes: 2