我需要从特定网址下载图片。当我的站点驻留在本地IIS中时,我的代码正常工作,但当它驻留在外部托管服务器中时甚至无法生成异常时无法正常工作。我不知道出了什么问题。任何的想法?
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;
}