I'm trying to use a local c# app to pull some images off a website to files on my local machine. I'm using the code listed below. I've tried both ASCII encoding and UTF8 encoding but the final file is not an correct. Does anyone see what I'm doing wrong? The url is active and correct and show the image just fine when I put the address in my browser.
private void button1_Click(object sender, EventArgs e) { HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create("http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg"); // returned values are returned as a stream, then read into a string String lsResponse = string.Empty; HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse(); using (StreamReader lxResponseStream = new StreamReader(lxResponse.GetResponseStream())) { lsResponse = lxResponseStream.ReadToEnd(); lxResponseStream.Close(); } byte[] lnByte = System.Text.UTF8Encoding.UTF8.GetBytes(lsResponse); System.IO.FileStream lxFS = new FileStream("34891.jpg", FileMode.Create); lxFS.Write(lnByte, 0, lnByte.Length); lxFS.Close(); MessageBox.Show("done"); }
If you call the GetRequestStream method, you must use the GetResponse method to retrieve the response. If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.
The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.
HttpWebRequest does not implement IDisposable so it does not require disposing. just set the httprequest object to null once your done with it.
This class contains support for HTTP-specific uses of the properties and methods of the WebResponse class. The HttpWebResponse class is used to build HTTP stand-alone client applications that send HTTP requests and receive HTTP responses.
nice image :D
try using the following code:
you needed to use a BinaryReader, 'cause an image file is binary data and thus not encoded in UTF or ASCII
edit: using'ified
HttpWebRequest lxRequest = (HttpWebRequest)WebRequest.Create( "http://www.productimageswebsite.com/images/stock_jpgs/34891.jpg"); // returned values are returned as a stream, then read into a string String lsResponse = string.Empty; using (HttpWebResponse lxResponse = (HttpWebResponse)lxRequest.GetResponse()){ using (BinaryReader reader = new BinaryReader(lxResponse.GetResponseStream())) { Byte[] lnByte = reader.ReadBytes(1 * 1024 * 1024 * 10); using (FileStream lxFS = new FileStream("34891.jpg", FileMode.Create)) { lxFS.Write(lnByte, 0, lnByte.Length); } } } MessageBox.Show("done");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With