首页 - 代码 - C#

C#柯乐义下载图片类

using System.IO;
using System.Net;

namespace HoverTree.HoverTreeFrame.HvtImage
{
/// <summary>
/// 柯乐义下载图片类
/// by 何问起
/// </summary>
public class KeleyiImgDownloader
{
/// <summary>
/// 下载图片
/// </summary>
/// <param name="picUrl">图片Http地址</param>
/// <param name="savePath">保存路径</param>
/// <param name="timeOut">Request最大请求时间,如果为-1则无限制,单位为毫秒</param>
/// <returns></returns>
public static bool DownloadPicture(string picUrl, string savePath, int timeOut)
{
if (string.IsNullOrWhiteSpace(picUrl))
return false;

bool value = false;
WebResponse response = null;
Stream stream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
if (timeOut != -1) request.Timeout = timeOut;
response = request.GetResponse();
stream = response.GetResponseStream();
////类型 非 文本
//if (!response.ContentType.ToLower().StartsWith("text/"))
// value = SaveBinaryFile(response, savePath);
//类型为图片
if (response.ContentType.ToLower().StartsWith("image"))
value = SaveBinaryFile(response, savePath);
//keleyi.com

}
catch
{
value = false;
}
finally
{
if (stream != null) stream.Close();
if (response != null) response.Close();
}
return value;
}
//参考:http://hovertree.com/h/bjaf/5dth2dp4.htm

private static bool SaveBinaryFile(WebResponse response, string savePath)
{
bool value = false;
byte[] buffer = new byte[1024];
Stream outStream = null;
Stream inStream = null;
try
{
if (File.Exists(savePath)) File.Delete(savePath);
outStream = File.Create(savePath);
inStream = response.GetResponseStream();
int l;
do
{
l = inStream.Read(buffer, 0, buffer.Length);
if (l > 0) outStream.Write(buffer, 0, l);
} while (l > 0);
value = true;
}
finally
{
if (outStream != null) outStream.Close();
if (inStream != null) inStream.Close();
}
return value;
}
}
}