fbpx Download a File from the Internet | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Download a File from the Internet

Problem

You want to download a file from a web site on the Internet.

Solution

Use the DownloadFile() method from the .NET Framework’s System.Net.WebClient class to download a file:

PS >$source = "http://www.leeholmes.com/favicon.ico" PS >$destination = "c:\temp\favicon.ico" PS > PS >$wc = NewObject System.Net.WebClient PS >$wc.DownloadFile($source, $destination)

Discussion

The System.Net.WebClient class from the .NET Framework lets you easily upload and download data from remote web servers.

The WebClient class acts much like a web browser, in that you can specify a user agent, proxy (if your outgoing connection requires one), and even credentials.

All web browsers send a user agent identifier along with their web request. This identifier tells the web site what application is making the request—such as Internet Explorer, Firefox, or an automated crawler from a search engine. Many web sites check this user agent identifier to determine how to display the page. Unfortunately, many fail entirely if they can’t determine the user agent for the incoming request. To make the System.Net.WebClient identify itself as Internet Explorer, use the following commands, instead:

$userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)" $wc = NewObject System.Net.WebClient $wc.Headers.Add("useragent", $userAgent)

Notice that the solution uses a fully qualified path for the destination file. This is an important step, as the DownloadFile() method saves its files to the directory in which PowerShell.exe started (the root of your user profile directory by default) otherwise.

You can use the DownloadFile() method to download web pages just as easily as you download files—you need to supply only an URL as a source (such as http://blogs. msdn.com/powershell/rss.xml ) instead of a filename. If you ultimately intend to parse or read through the downloaded page, the DownloadString() method may be more appropriate.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say