Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to download image from a specific url. My code works properly when my site reside in Local IIS but not work when it reside in external hosting server even generate no exception. I don't know what my wrong is? If u can please suggest me.

public void DownloadFile(string source, string destination)
{
HttpWebRequest webRequest = HttpWebRequest.Create(source) as HttpWebRequest;
HttpWebResponse resp = webRequest.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
if (resp.ContentType.Contains("image/"))
{
byte[] imageContent = ProcessImageStream(resp);
MemoryStream ms = new MemoryStream(imageContent);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
img.Save(destination);
}
}
}

public static byte[] ProcessImageStream(HttpWebResponse resp)
{
byte[] streamContent;
MemoryStream memStream = new MemoryStream();
const int BUFFER_SIZE = 4096;
int iRead = 0;
Int64 iSize = 0;
memStream.SetLength(BUFFER_SIZE);
try
{
using (memStream)
{
while (true)
{
iRead = 0;
byte[] respBuffer = new byte[BUFFER_SIZE];
iRead = resp.GetResponseStream().Read(respBuffer, 0, BUFFER_SIZE);
if (iRead == 0)
{
break;
}
iSize += iRead;
memStream.SetLength(iSize);
memStream.Write(respBuffer, 0, iRead);
}
streamContent = memStream.ToArray();
}
}
catch (Exception ex)
{
throw ex;
}
return streamContent;
}
Posted
Comments
suzand 25-Mar-14 9:36am    
Please help me...

1 solution

Check the value of resp.StatusCode, maybe its not returning HttpStatusCode.OK. For this, you can write some code in the else block of "if (resp.StatusCode == HttpStatusCode.OK)" statement.

Another thing to note is that your file will be downloaded in a folder on your server and not on you local drive. In other words, file will be saved on the computer where the code is executing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900