ファイルをダウンロードする

「System.Net.WebClient」はファイルのダウンロード/アップロードができます。

ファイルのダウンロード(ファイルを保存)

ファイルの読み込み処理 - PowerShell Memoのサンプルと同様です。

ダウンロードしたファイルを保存する
MSH C:\> $url="http://www.google.co.jp/intl/ja_jp/images/logo.gif"
MSH C:\> $webClient = new-object System.Net.WebClient
MSH C:\> $webClient.DownloadFile($url, "C:\logo.gif")

ファイルのダウンロード(Stream)

ダウンロードしたファイルの内容を取得する
MSH C:\> $url="http://www.google.co.jp/index.html"
MSH C:\> $webClient = new-object System.Net.WebClient
MSH C:\> $stream = $webClient.OpenRead($url)
MSH C:\> $stream.getType().fullname
System.Net.ConnectStream
MSH C:\> $reader = new-object System.IO.StreamReader($stream)
MSH C:\> $reader.ReadToEnd()
<html><head><meta http-equiv="content-type" content="text/html; 
(中略)
  • OpenReadメソッドで「ConnectStream」を取得。
  • Stream型のオブジェクトは「System.IO.StreamReader」で読み込み処理を行います。
  • ReadToEndメソッドはStreamを最後まで読み込みます。
  • 1行ずつ読み込む場合はReadLineメソッドです。