WebClient

WebClient provides a higher-level interface to network resources than WebRequest. DownloadData( ) and DownloadFile( ) retrieve resources from a URI into a byte array or a file. UploadData( ) and UploadFile( ) sends the contents of a byte array or a file to a resource identified by a URI. Use WebClient to rewrite Snarf.cs as:

// Snarf2.cs
// Run Snarf.exe <http-uri> to retrieve a web page
using System;
using System.Net;
using System.Text;
class Snarf {
  static void Main(string[ ] args) {
    WebClient wc = new WebClient( );
    byte[ ] buffer = wc.DownloadData(args[0]);
    string doc = Encoding.ASCII.GetString(buffer);
    Console.WriteLine(doc);
  }
}

Get C# in a Nutshell, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.