如何使用vb.net在列表框中下载多个文件

发布于 2025-02-13 19:26:27 字数 169 浏览 1 评论 0原文

我想下载倍数文件和列表框中的下载链接,是否有任何方法可以使用webclient进行此操作,我看到人们通过文件逐文件做到这一点,看起来很困难,我想显示当前下载速度当前文件大小总过程的进度

I want to download multiples files and the download links in list box, Is there any way to do that using WebClient, i saw people do that by download file by file by it look difficult way and i want to show current downloading speed ,current file size and progress of total process

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

维持三分热 2025-02-20 19:26:27

我以这种方式解决了这个建议:

Imports System.Net
Public Class Form1
    Private WithEvents DonloadFile As WebClient
    Dim stopwatch As Stopwatch = New Stopwatch

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.SelectedIndex = 0
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        stopwatch.Start()
        DonloadFile = New WebClient
        Try
            DonloadFile.DownloadFileAsync(New Uri(ListBox1.SelectedItem.ToString), "C:\Users\" & Environment.UserName & "\Desktop\" & IO.Path.GetFileName(ListBox1.SelectedItem.ToString))
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub DonloadFile_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles DonloadFile.DownloadProgressChanged
        Dim y As Integer = (e.BytesReceived / 1024) / 1024
        Label6.Text = "Download Speed: " & String.Format("{0} MB/s", (y / (stopwatch.Elapsed.TotalSeconds)).ToString("0.00"))
        Label2.Text = "Current File Size: " & Math.Round(e.TotalBytesToReceive / (1024 * 1024), 1) & " MB"
        Label3.Text = "Current File Persent: " & e.ProgressPercentage
        Label1.Text = "Total Files: " & ListBox1.Items.Count.ToString()
        If ListBox1.Items.Count.ToString > (ListBox1.SelectedIndex + 1) Then
            If e.ProgressPercentage = 100 Then
                ListBox1.SelectedIndex += 1
            End If
        Else
            MessageBox.Show("Download completed successful", "Info")
        End If
    End Sub

    Private Sub DonloadFile_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs) Handles DonloadFile.DownloadDataCompleted
        stopwatch.Reset()
    End Sub
End Class

感谢@fawlty

I solved this proplem by that way:

Imports System.Net
Public Class Form1
    Private WithEvents DonloadFile As WebClient
    Dim stopwatch As Stopwatch = New Stopwatch

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListBox1.SelectedIndex = 0
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        stopwatch.Start()
        DonloadFile = New WebClient
        Try
            DonloadFile.DownloadFileAsync(New Uri(ListBox1.SelectedItem.ToString), "C:\Users\" & Environment.UserName & "\Desktop\" & IO.Path.GetFileName(ListBox1.SelectedItem.ToString))
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub DonloadFile_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles DonloadFile.DownloadProgressChanged
        Dim y As Integer = (e.BytesReceived / 1024) / 1024
        Label6.Text = "Download Speed: " & String.Format("{0} MB/s", (y / (stopwatch.Elapsed.TotalSeconds)).ToString("0.00"))
        Label2.Text = "Current File Size: " & Math.Round(e.TotalBytesToReceive / (1024 * 1024), 1) & " MB"
        Label3.Text = "Current File Persent: " & e.ProgressPercentage
        Label1.Text = "Total Files: " & ListBox1.Items.Count.ToString()
        If ListBox1.Items.Count.ToString > (ListBox1.SelectedIndex + 1) Then
            If e.ProgressPercentage = 100 Then
                ListBox1.SelectedIndex += 1
            End If
        Else
            MessageBox.Show("Download completed successful", "Info")
        End If
    End Sub

    Private Sub DonloadFile_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs) Handles DonloadFile.DownloadDataCompleted
        stopwatch.Reset()
    End Sub
End Class

thanks for @Fawlty

雪花飘飘的天空 2025-02-20 19:26:27

这是我写的一些代码,以演示如何做到这一点。我创建了一个filedownloader类,因为下载完成后,您可以获取源URL和目标文件名。我还添加了一个进度活动。仅使用webclient类的问题是,您将失去在事件中正在处理哪个文件的跟踪。

Imports System.ComponentModel
Imports System.Net

    ' A class for downloading files, with progress and finished events
Public Class FileDownloader

    ' Private storage
    Private FileURL As String = ""
    Private SaveToPath As String = ""

    ' A class to return our result in
    Public Class FileDownloaderFileDownloadedEventArgs
        Public Property DownloadedURL As String
        Public Property SaveToPath As String
        Public Sub New(DownloadedURL As String, SaveToPath As String)
            Me.DownloadedURL = DownloadedURL
            Me.SaveToPath = SaveToPath
        End Sub
    End Class

    ' A class to show progress
    Public Class FileDownloaderProgressEventArgs
        Public Property DownloadURL As String
        Public Property SaveToPath As String
        Public Property TotalBytes As Long
        Public Property ProgressBytes As Long
        Public Property ProgressPercent As Integer
        Public Property UserState As Object

        Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
            Me.DownloadURL = DownloadURL
            Me.SaveToPath = SaveToPath
            Me.TotalBytes = TotalBytes
            Me.ProgressBytes = ProgressBytes
            Me.ProgressPercent = ProgressPercent
            Me.UserState = UserState
        End Sub
    End Class

    ' The event to raise when the file is downloaded
    Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
    ' The event to raise when there is progress
    Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)

    ' Pass in the URL and FilePath when creating the downloader object
    Public Sub New(FileURL As String, SaveToPath As String)
        Me.FileURL = FileURL
        Me.SaveToPath = SaveToPath
    End Sub

    ' Call Download() to do the work
    Public Sub Download()
        Using wc As New WebClient
            AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
            AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
            wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
        End Using
    End Sub

    ' Catch the download complete and raise our event
    Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
    End Sub

    Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
        ' Some code you want to run after each file has downloaded
        RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
    End Sub
End Class

#Region "How to use the FileDownloader class"

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' Loop the URLs in the ListBox
        For Each item In ListBox1.Items
            ' Create a FileDownloader object to handler each one
            Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
            ' Attach the event handlers
            AddHandler FD.FileDownloaded, AddressOf FileDownloaded
            AddHandler FD.Progress, AddressOf Progress
            ' Start the download
            FD.Download()
        Next
    End Sub

    ' Event handler for file download completed
    Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
        tb_Log.AppendText(e.DownloadedURL & "  Downloaded To:  " & e.SaveToPath & vbCrLf)
    End Sub

    ' Event handler for progress
    Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
        tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
    End Sub

#End Region

Here is some code I wrote to demonstrate how you could do this. I created a FileDownloader class as this will allow you to get the source url and destination filename when the download completes. I have also added an event for progress. The problem with just using the WebClient class on its own is that you lose track of which file is being processed in the events.

Imports System.ComponentModel
Imports System.Net

    ' A class for downloading files, with progress and finished events
Public Class FileDownloader

    ' Private storage
    Private FileURL As String = ""
    Private SaveToPath As String = ""

    ' A class to return our result in
    Public Class FileDownloaderFileDownloadedEventArgs
        Public Property DownloadedURL As String
        Public Property SaveToPath As String
        Public Sub New(DownloadedURL As String, SaveToPath As String)
            Me.DownloadedURL = DownloadedURL
            Me.SaveToPath = SaveToPath
        End Sub
    End Class

    ' A class to show progress
    Public Class FileDownloaderProgressEventArgs
        Public Property DownloadURL As String
        Public Property SaveToPath As String
        Public Property TotalBytes As Long
        Public Property ProgressBytes As Long
        Public Property ProgressPercent As Integer
        Public Property UserState As Object

        Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
            Me.DownloadURL = DownloadURL
            Me.SaveToPath = SaveToPath
            Me.TotalBytes = TotalBytes
            Me.ProgressBytes = ProgressBytes
            Me.ProgressPercent = ProgressPercent
            Me.UserState = UserState
        End Sub
    End Class

    ' The event to raise when the file is downloaded
    Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
    ' The event to raise when there is progress
    Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)

    ' Pass in the URL and FilePath when creating the downloader object
    Public Sub New(FileURL As String, SaveToPath As String)
        Me.FileURL = FileURL
        Me.SaveToPath = SaveToPath
    End Sub

    ' Call Download() to do the work
    Public Sub Download()
        Using wc As New WebClient
            AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
            AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
            wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
        End Using
    End Sub

    ' Catch the download complete and raise our event
    Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
        RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
    End Sub

    Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
        ' Some code you want to run after each file has downloaded
        RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
    End Sub
End Class

#Region "How to use the FileDownloader class"

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        ' Loop the URLs in the ListBox
        For Each item In ListBox1.Items
            ' Create a FileDownloader object to handler each one
            Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
            ' Attach the event handlers
            AddHandler FD.FileDownloaded, AddressOf FileDownloaded
            AddHandler FD.Progress, AddressOf Progress
            ' Start the download
            FD.Download()
        Next
    End Sub

    ' Event handler for file download completed
    Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
        tb_Log.AppendText(e.DownloadedURL & "  Downloaded To:  " & e.SaveToPath & vbCrLf)
    End Sub

    ' Event handler for progress
    Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
        tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
    End Sub

#End Region
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文