Back to Top

Monthly Archives: 12月 2016

VB.NET WebClientでUriをダウンロード

WebClientクラスを使用して、URL(URI)からデータをダウンロードする方法を記載します。

・System.Netをインポートする

指定URL(URI)から文字列としてダウンロードする

Dim url As String = "http://microsoft.com"

Dim html As String

Using WebCl As New WebClient()
    WebCl.Encoding = System.Text.Encoding.UTF8      '文字コードを指定
    html = WebCl.DownloadString(url)                'データを文字列としてダウンロードする
End Using

'ダウンロードしたデータを表示
Console.WriteLine(html)

 

指定URL(URI)からバイナリーデータとしてダウンロードする

Dim Data As Byte()
Using WebCl As New WebClient()
    Data = WebCl.DownloadData(url)                  'データをバイト配列にダウンロードする
End Using

'ダウンロードしたデータを表示する
Dim str As String = System.Text.Encoding.UTF8.GetString(Data)    'バイト配列を文字列に変換
Console.WriteLine(str)

 

ストリームを使用して、指定URL(URI)を読み込む

Dim str As String

Using WebCl As New WebClient()
    Dim dt As System.IO.Stream = WebCl.OpenRead(url)                        'データを読み取るStreamを開く
    Dim sr As New System.IO.StreamReader(dt, System.Text.Encoding.UTF8)
    str = sr.ReadToEnd()
    dt.Close()
End Using

'ダウンロードしたデータを表示する
Console.WriteLine(str)

 

指定URL(URI)からファイルをダウンロードする

Dim url As String = "\\192.168.2.10\Share/sample.txt"
Dim fileName As String = "C:\work\sample.txt"

Using WebCl As New WebClient()
    'IDとパスワードがいる場合設定
    'WebCl.Credentials = New NetworkCredential("id", "password")

    WebCl.DownloadFile(url, fileName)                 'ファイルをダウンロードする
End Using

 

 

VB.NET ping送信

Ping送信には、方法がいくつかあります。その一部を記載します。

・System.Net.NetworkInformationをインポートしておきます。

My.Computer.Network.Pingメソッドを使用する方法

If My.Computer.Network.Ping("yahoo.com") Then
    MessageBox.Show("Pingに成功")
Else
    MessageBox.Show("Pingに失敗")
End If

 

Pingクラスを使用する方法

'Pingオブジェクトを作成
Using ping As New System.Net.NetworkInformation.Ping()
    'Pingを送信し結果を取得する
    Dim reply As System.Net.NetworkInformation.PingReply = ping.Send("yahoo.com")

    If reply.Status = System.Net.NetworkInformation.IPStatus.Success Then
        MessageBox.Show(String.Format("PingReply {0}:bytes={1} time={2}ms",
                reply.Address, reply.Buffer.Length, reply.RoundtripTime))
    Else
        MessageBox.Show(String.Format("Ping送信に失敗。({0})", reply.Status))
    End If
End Using

・IPStatus列挙体