VB.Net WebClient 이용해 파일 다운로드 방법
vb.net WebClient 이용해 파일 다운로드 WebClient 사용법
VB.Net에서 WebClient 클래스를 이용해 파일을 다운로드하는 방법에 대해 알려드리겠습니다.
WebClient 클래스는 System.Net 네임스페이스에 속하며, HTTP 리소스에 대한 간단한 작업을 수행할 수 있는 고수준의 클래스입니다.
WebClient 클래스를 사용하기 위해서는 다음과 같이 Imports 문을 통해 System.Net 네임스페이스를 참조해야 합니다.
Imports System.Net
그리고 다음과 같이 WebClient 객체를 생성할 수 있습니다.
Dim webClient As New WebClient()
WebClient 객체를 생성한 후, DownloadFile 메서드를 사용하여 원하는 파일을 다운로드할 수 있습니다. DownloadFile 메서드는 두 개의 매개변수를 받습니다. 첫 번째 매개변수는 다운로드할 파일의 URL을 나타내는 Uri 객체이고, 두 번째 매개변수는 다운로드할 파일의 로컬 경로를 나타내는 문자열입니다. 예를 들어, 다음과 같이 VLC 미디어 플레이어를 다운로드할 수 있습니다.
webClient.DownloadFile(New Uri("https://get.videolan.org/vlc/2.2.6/win32/vlc-2.2.6-win32.exe"), "C:\vlc.exe")
이렇게 하면,https://get.videolan.org/vlc/2.2.6/win32/vlc-2.2.6-win32.exe에서 파일을 다운로드하여 C:\vlc.exe 에 저장합니다.
DownloadFile 메서드는 동기적으로 작동하므로, 다운로드가 완료될 때까지 프로그램이 멈춥니다. 만약 다운로드가 완료될 때까지 기다리지 않고, 다른 작업을 계속하고 싶다면, DownloadFileAsync 메서드를 사용할 수 있습니다. DownloadFileAsync 메서드는 DownloadFile 메서드와 같은 매개변수를 받지만, 비동기적으로 작동하므로, 다운로드가 완료되지 않아도 프로그램이 계속 실행됩니다. 예를 들어, 다음과 같이 VLC 미디어 플레이어를 비동기적으로 다운로드할 수 있습니다.
webClient.DownloadFileAsync(New Uri(" https://get.videolan.org/vlc/2.2.6/win32/vlc-2.2.6-win32.exe "), "C:\vlc.exe")
이렇게 하면, 다운로드가 백그라운드에서 진행되고, 프로그램이 다른 작업을 할 수 있습니다.
DownloadFileAsync 메서드를 사용할 때는, 다운로드의 진행 상황이나 완료 여부를 알기 위해 WebClient 클래스의 이벤트를 사용할 수 있습니다. WebClient 클래스는 다음과 같은 이벤트를 제공합니다.
- DownloadProgressChanged: 다운로드의 진행 상황이 변경될 때 발생하는 이벤트입니다. 이벤트 핸들러는 DownloadProgressChangedEventArgs 객체를 매개변수로 받으며, 이 객체는 다운로드된 바이트 수, 전체 바이트 수, 진행률 등의 정보를 포함합니다.
- DownloadFileCompleted: 다운로드가 완료되었을 때 발생하는 이벤트입니다. 이벤트 핸들러는 AsyncCompletedEventArgs 객체를 매개변수로 받으며, 이 객체는 다운로드가 성공적으로 완료되었는지, 취소되었는지, 오류가 발생했는지 등의 정보를 포함합니다.
이러한 이벤트를 사용하여, 다운로드의 진행 상황을 표시하거나, 다운로드가 완료되면 메시지를 보여주는 등의 작업을 수행할 수 있습니다. 예를 들어, 다음과 같은 코드를 참고하실 수 있습니다.
예제 1
' WebClient 객체를 생성하고, 이벤트 핸들러를 등록합니다.
Dim webClient As New WebClient()
AddHandler webClient.DownloadProgressChanged, AddressOf DownloadProgressChanged
AddHandler webClient.DownloadFileCompleted, AddressOf DownloadFileCompleted
' 다운로드할 파일의 URL과 로컬 경로를 정의합니다.
Dim downloadUrl As String = "https://get.videolan.org/vlc/2.2.6/win32/vlc-2.2.6-win32.exe"
Dim localPath As String = "C:\vlc.exe"
' 비동기적으로 파일을 다운로드합니다.
webClient.DownloadFileAsync(New Uri(downloadUrl), localPath)
' 다운로드의 진행 상황을 표시하는 이벤트 핸들러입니다.
Private Sub DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
' 진행률을 백분율로 표시합니다.
Console.WriteLine("Downloading {0}%...", e.ProgressPercentage)
End Sub
' 다운로드가 완료되면 메시지를 보여주는 이벤트 핸들러입니다.
Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
' 다운로드가 성공적으로 완료되었는지 확인합니다.
If e.Cancelled Then
Console.WriteLine("Download cancelled.")
ElseIf e.Error IsNot Nothing Then
Console.WriteLine("Download failed: {0}", e.Error.Message)
Else
Console.WriteLine("Download completed.")
End If
End Sub
예제 2
Imports System.Net
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim client As New WebClient()
AddHandler client.DownloadProgressChanged, AddressOf ShowDownloadProgress
AddHandler client.DownloadFileCompleted, AddressOf OnDownloadComplete
client.DownloadFileAsync(New Uri("http://media.kgb.co.kr/intranet/20111123_hankyungTV02.wmv"), "C:\test.wmv")
End Sub
Private Sub OnDownloadComplete(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
If Not e.Cancelled AndAlso e.Error Is Nothing Then
MessageBox.Show("Download success")
Else
MessageBox.Show("Download failed")
End If
End Sub
Private Sub ShowDownloadProgress(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
ProgressBar1.Value = e.ProgressPercentage
End Sub
End Class
WebClient 예제 파일 첨부했습니다.
이상으로, VB.Net에서 WebClient 클래스를 이용해 파일을 다운로드하는 방법에 대해 설명드렸습니다.