你的位置:首页 > ASP.net教程

[ASP.net教程]使用.Net中的HttpWebRequest类和HttpWebResponse类获取web文件


string url = "http://pic.maizuo.com/usr/100002174/0e495857e71e57b9486aecec788d557e.tmp";
WebRequest wreq = WebRequest.Create(url);
WebResponse wres = wreq.GetResponse();
long len = wres.ContentLength;
byte[] bytes=new byte[len];
Stream ss = wres.GetResponseStream();
string path = Server.MapPath("~/images/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
int idx = url.LastIndexOf(".");
string suffix = url.Substring(idx);//获得上传的图片的后缀名
if (suffix.Contains("tmp"))
{
suffix = ".jpg";
}
string pictureName = DateTime.Now.Ticks.ToString() + suffix;
FileStream os = new FileStream(path + pictureName, FileMode.OpenOrCreate, FileAccess.Write);
int c = 0;
while ((c = ss.Read(bytes, 0, bytes.Length)) > 0)
{
os.Write(bytes, 0, c);
}
os.Close();
ss.Close();