使用Webclient和DownloadFile()获得.txt文件而不是.jpg文件; [英] Get .txt file instead of .jpg - using Webclient and DownloadFile();

查看:72
本文介绍了使用Webclient和DownloadFile()获得.txt文件而不是.jpg文件;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取.txt文件而不是.jpg-使用WebclientDownloadFile();

Get .txt file instead of .jpg - using Webclient and DownloadFile();

我正在尝试从以下URL下载.jpg:

I'm trying to download the .jpg from this URL:

http://1. bp.blogspot.com/_pK6J3MTn5co/S6kuH3aqbeI/AAAAAAAACUY/06axvmjU91k/s1600-h/avengers02_B&W_UL.jpg

使用此代码:

private void TEST_button1_Click(object sender, EventArgs e)
{
    WebClient MyDownloader = new WebClient();
    MyDownloader.DownloadFile(@"http://1.bp.blogspot.com/_pK6J3MTn5co/S6kuH3aqbeI/AAAAAAAACUY/06axvmjU91k/s1600-h/avengers02_B&W_UL.jpg", @"c:\test.jpg");
}

但是,当我运行此程序时,最终得到一个名为 test.jpg 的文件,其中包含html标记...:

However, when I run this, I end up with a file called test.jpg, which contains html mark up... :

<html>
<head>
<title>avengers02_B&amp;W_UL.jpg (image)</title>
<script type="text/javascript">
<!--
if (top.location != self.location) top.location = self.location;
// -->
</script>
</head>
<body bgcolor="#ffffff" text="#000000">
<img src="http://1.bp.blogspot.com/_pK6J3MTn5co/S6kuH3aqbeI/AAAAAAAACUY/06axvmjU91k/s1600/avengers02_B%26W_UL.jpg" alt="[avengers02_B&amp;W_UL.jpg]" border=0>
</body>
</html>

如何下​​载实际的.jpg?

How can I download the actual .jpg?

非常感谢您的帮助-谢谢!

Any help is greatly appreciated - thank you!

推荐答案

有一种方法可以做到这一点.首先,您将HTML内容下载到字符串中,然后提取正确的图像URL.然后使用正确的URL下载文件.

There is a way to do it. First you download the HTML content to a string and extract the correct image URL. Then use the correct URL to download the file.

 WebClient client = new WebClient();
 var path = @"http://1.bp.blogspot.com/_pK6J3MTn5co/S6kuH3aqbeI/AAAAAAAACUY/06axvmjU91k/s1600-h/avengers02_B&W_UL.jpg";

 var content = client.DownloadString(path);
 System.Text.RegularExpressions.Regex regex = new Regex(@"(?<=<img\s+[^>]*?src=(?<q>['""]))(?<url>.+?)(?=\k<q>)");
 var match = regex.Match(content);
 if (match.Success)
 {
     client.DownloadFile(match.Value, @"e:\test1.jpg");
 } 

这篇关于使用Webclient和DownloadFile()获得.txt文件而不是.jpg文件;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆