Tải bản đầy đủ - 0 (trang)
10-3. Download Data over HTTP or FTP

10-3. Download Data over HTTP or FTP

Tải bản đầy đủ - 0trang

CHAPTER 10 ■ NETWORKING



DownloadFile



Downloads data from a specified URI and saves it to a specified local file.



DownloadFileAsync



Same as DownloadFile, but performs the data transfer using a thread-pool thread

so that the calling thread does not block. Add an event handler to the

DownloadFileCompleted event to receive notification that the operation has

completed.



DownloadString



Returns a string that contains the data from a specified URI.



DownloadStringAsync



Same as DownloadString, but performs the data transfer using a thread-pool

thread so that the calling thread does not block. Add an event handler to the

DownloadStringCompleted event to receive notification that the operation has

completed.



The asynchronous download allows you to download data as a background task using a thread from

the thread pool (discussed in recipe 4-1). When the download is finished or fails, the thread calls the

appropriate OnXXX virtual methods that raise the corresponding event on the WebClient object, which

you can handle using a method that matches the signature of the System.ComponentModel.

AsyncCompletedEventHandler delegate if you don’t want to derive a type from WebClient and override the

virtual method. However, the WebClient object can handle only a single concurrent asynchronous

download, making a WebClient object suitable for the background download of large single sets of data

but not for the download of many files concurrently. (You could, of course, create multiple WebClient

objects to handle multiple downloads.) You can cancel the outstanding asynchronous download using

the method CancelAsync.



■ Tip The WebClient class derives from System.ComponentModel.Component, so you can add it to the Visual

Studio Form Designer Toolbox in order to allow you to easily set the properties or define the event handlers in a

Windows Forms–based application.



The Code

The following example downloads a specified resource from a URI as a string and, since it is an HTML

page, parses it for any fully qualified URLs that refer to GIF files. It then downloads each of these files to

the local hard drive.

using

using

using

using



System;

System.IO;

System.Net;

System.Text.RegularExpressions;



namespace Apress.VisualCSharpRecipes.Chapter10

{

class Recipe10_03

{



487



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



private static void Main()

{

// Specify the URI of the resource to parse.

string srcUriString = "http://www.apress.com";

Uri srcUri = new Uri(srcUriString);

// Create a WebClient to perform the download.

WebClient client = new WebClient();

Console.WriteLine("Downloading {0}", srcUri);

// Perform the download getting the resource as a string.

string str = client.DownloadString(srcUri);

// Use a regular expression to extract all HTML

// elements and extract the path to any that reference

// files with a gif, jpg, or jpeg extension.

MatchCollection matches = Regex.Matches(str,

".*?\\.(gif|jpg|jpeg)).*?>",

RegexOptions.Singleline | RegexOptions.IgnoreCase);

// Try to download each referenced image file.

foreach(Match match in matches)

{

var urlGrp = match.Groups["url"];

if (urlGrp != null && urlGrp.Success)

{

Uri imgUri = null;

// Determine the source URI.

if (urlGrp.Value.StartsWith("http"))

{

// Absolute

imgUri = new Uri(urlGrp.Value);

}

else if (urlGrp.Value.StartsWith("/"))

{

// Relative

imgUri = new Uri(srcUri, urlGrp.Value);

}

else

{

// Skip it.

Console.WriteLine("Skipping image {0}", urlGrp.Value);

}



488



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



if (imgUri != null)

{

// Determine the local file name to use.

string fileName =

urlGrp.Value.Substring(urlGrp.Value.LastIndexOf('/')+1);

try

{

// Download and store the file.

Console.WriteLine("Downloading {0} to {1}",

imgUri.AbsoluteUri, fileName);

client.DownloadFile(imgUri, fileName);

}

catch

{

Console.WriteLine("Failed to download {0}",

imgUri.AbsoluteUri);

}

}

}

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter");

Console.ReadLine();

}

}

}



■ Note The regular expression used in the example is simple and is not designed to cater to all possible URL

structures. Recipes 2-5 and 2-6 discuss regular expressions.



Notes

You may also want to upload data to resources specified as a URI, although this technique is not as

commonly used. The WebClient class also provides methods for performing uploads that are equivalent

to the download methods discussed previously:





OpenWrite







OpenWriteAsync







UploadData







UploadDataAsync



489



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING







UploadFile







UploadFileAsync







UploadString







UploadStringAsync



10-4. Download a File and Process It Using a Stream

Problem

You need to retrieve a file from a web site, but you do not want or do not have permission to save it

directly to the hard drive. Instead, you want to process the data in your application directly in memory.



Solution

Use the System.Net.WebRequest class to create your request, the System.Net.WebResponse class to retrieve

the response from the web server, and some form of reader (typically a System.IO.StreamReader for

HTML or text data or a System.IO.BinaryReader for a binary file) to parse the response data.



■ Tip You could also use the OpenRead method of the System.Net.WebClient class to open a stream. However,

the additional capabilities of the WebRequest and WebResponse classes give you more control over the operation of

the network request.



How It Works

Opening and downloading a stream of data from the Web using the WebRequest and WebResponse classes

takes the following four basic steps:

1.



Use the static method Create of the WebRequest class to specify the page you

want. This method returns a WebRequest-derived object, depending on the type

of URI you specify. For example, if you use an HTTP URI (with the scheme

http:// or https://), you will create an HttpWebRequest instance. If you use a

file system URI (with the scheme file://), you will create a FileWebRequest

instance. In the .NET Framework 2.0 and later, you can also use an FTP URL

(with the scheme ftp://), which will create an FtpWebRequest.



2.



Use the GetResponse method of the WebRequest object to return a WebResponse

object for the page. If the request times out, a System.Net.WebException will be

thrown. You can configure the timeout for the network request through the

WebRequest.Timeout property in milliseconds (the default value is 100000).



490



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



3.



Create a StreamReader or a BinaryReader that wraps the stream returned by the

WebResponse.GetResponseStream method.



4.



Perform any steps you need to with the stream contents.



The Code

The following example retrieves and displays a graphic and the HTML content of a web page. Figure 10-1

shows the output.

using

using

using

using

using



System;

System.Net;

System.IO;

System.Drawing;

System.Windows.Forms;



namespace Apress.VisualCSharpRecipes.Chapter10

{

public partial class Recipe10_04 : Form

{

public Recipe10_04()

{

InitializeComponent();

}

protected override void OnLoad(EventArgs e)

{

base.OnLoad(e);

string picUri = "http://www.apress.com/img/img05/Hex_RGB4.jpg";

string htmlUri = "http://www.apress.com";

// Create the requests.

WebRequest requestPic = WebRequest.Create(picUri);

WebRequest requestHtml = WebRequest.Create(htmlUri);

// Get the responses.

// This takes the most significant amount of time, particularly

// if the file is large, because the whole response is retrieved.

WebResponse responsePic = requestPic.GetResponse();

WebResponse responseHtml = requestHtml.GetResponse();

// Read the image from the response stream.

pictureBox1.Image = Image.FromStream(responsePic.GetResponseStream());



491



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

10-3. Download Data over HTTP or FTP

Tải bản đầy đủ ngay(0 tr)

×