IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

problème downloader multiple files


Sujet :

VB.NET

  1. #1
    Membre actif
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2018
    Messages
    321
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2018
    Messages : 321
    Points : 261
    Points
    261
    Par défaut problème downloader multiple files
    Bonsoir,

    j’arrive pas à télécharger 2 fichier à la fois avec listview. le premier fonctionne mais pas le deuxième. avez-vous une solution pour télécharger 2 fichier à la fois après a la suite.

    voici en image :
    Nom : Capture d’écran 2024-07-27 203929.png
Affichages : 140
Taille : 7,8 Ko

    mon code from1 :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    ....etc
    For Each Item As ListViewItem In ListView1.CheckedItems
                            Download.InfoDownloader(Item.Text, Item.SubItems(1).Text, Folder.SelectedPath)
                        Next
                        Download.Show()
    ...etc
    mon code avec download :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    Private WithEvents _Downloader As New WebFileDownloader
        Private counter As Integer = 0
     
        Public Sub InfoDownloader(Names As String, URL As String, destination As String)
            Dim lvi As New ListViewItem(Names)
            lvi.UseItemStyleForSubItems = False
            lvi.SubItems.Add("Vérifications en cours....").ForeColor = Color.DarkBlue
            lvi.ImageIndex = 0
            LvDownloads.Items.Add(lvi)
            Task.Factory.StartNew(Sub()
                                      AddHandler _Downloader.DownloadProgressChanged, New WebFileDownloader.ProgressChangedEventHandler(AddressOf download_DownloadProgress)
                                      AddHandler _Downloader.DownloadCompleted, New WebFileDownloader.DownloadCompletedEventHandler(AddressOf download_DownloadComplete)
                                      _Downloader.DownloadFile(URL, Path.Combine(destination, Names & Path.GetExtension(URL)))
                                  End Sub)
        End Sub
     
        Private Sub download_DownloadComplete(sender As Object, e As DownloadCompletedArgs)
            If e.ErrorMessage Then
                LvDownloads.Invoke(Sub()
                                       LvDownloads.Items(counter).SubItems(1).Text = "Avec succès..."
                                       LvDownloads.Items(counter).SubItems(1).ForeColor = Color.Blue
                                   End Sub)
                If counter = LvDownloads.Items.Count Then
                    counter += 1
                Else
                    Exit Sub
                End If
            Else
                LvDownloads.Invoke(Sub()
                                       LvDownloads.Items(counter).SubItems(1).Text = "Erreur de téléchargement de la video"
                                       LvDownloads.Items(counter).SubItems(1).ForeColor = Color.Red
                                   End Sub)
            End If
        End Sub
     
        Private Sub download_DownloadProgress(sender As Object, e As DownloadProgressArgs)
            On Error Resume Next
            LvDownloads.Invoke(Sub()
                                   LvDownloads.Items(counter).SubItems(1).Text = "Téléchargement(" & FormatFileSize(e.BytesReceived) & " / " & FormatFileSize(e.TotalBytesReceived) & ") - " & e.ProgressPercentage & " %"
                                   LvDownloads.Items(counter).SubItems(1).ForeColor = Color.Green
                               End Sub)
        End Sub
        Private Function FormatFileSize(byteCount As Long) As String
            Dim suf As String() = {"Bytes", "KB", "MB", "GB"}
            If byteCount = 0 Then Return "0" & suf(0)
            Dim bytes As Long = Math.Abs(byteCount)
            Dim place As Integer = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)))
            Dim num As Double = Math.Round(bytes / Math.Pow(1024, place), 1)
            Return (Math.Sign(byteCount) * num).ToString() & " " & suf(place)
        End Function
     
        Private Sub Download_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            System.Net.ServicePointManager.DefaultConnectionLimit = 2
        End Sub
    End Class
    ma classe WebFileDownloader :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
     
    Imports System.Net
    Imports System.IO
     
    Class WebFileDownloader
     
        Public Delegate Sub ProgressChangedEventHandler(ByVal sender As Object, ByVal e As DownloadProgressArgs)
        Public Event DownloadProgressChanged As ProgressChangedEventHandler
        Public Delegate Sub DownloadCompletedEventHandler(ByVal sender As Object, ByVal e As DownloadCompletedArgs)
        Public Event DownloadCompleted As DownloadCompletedEventHandler
     
        Protected Overridable Sub OnDownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressArgs)
            RaiseEvent DownloadProgressChanged(Me, e)
        End Sub
     
        Protected Overridable Sub OnDownloadCompleted(ByVal sender As Object, ByVal e As DownloadCompletedArgs)
            RaiseEvent DownloadCompleted(Me, e)
        End Sub
     
        Sub DownloadFile(ByVal URL As String, ByVal Location As String)
            Try
                Dim uri As New Uri(URL)
                If ((uri.Scheme <> uri.UriSchemeHttp) And (uri.Scheme <> uri.UriSchemeHttps)) Then
                    Throw New Exception("URL invalide. L'URL doit commencer par ""http://"" ou ""https://"".")
                    Exit Sub
                End If
                Dim request As HttpWebRequest = CType(WebRequest.Create(New Uri(URL)), HttpWebRequest)
                With request
                    .Method = "GET"
                    .Timeout = 20000
                    .KeepAlive = True
                    .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"
                End With
                Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                    If response.StatusCode = HttpStatusCode.OK Then
                        Dim _ContentLenght As Integer = response.ContentLength
                        Using stream As Stream = response.GetResponseStream()
                            Using fs As New FileStream(Location, FileMode.Create, FileAccess.Write, FileShare.Write)
                                Dim buffer As Byte() = New Byte(4096 - 1) {}
                                Dim _TotalBytesReceived As Integer = 0
                                Dim isRead As Boolean = True
                                Do
                                    Dim readsize As Integer = stream.Read(buffer, 0, buffer.Length)
                                    If readsize = 0 Then
                                        isRead = False
                                        Exit Do
                                    End If
                                    _TotalBytesReceived += readsize
                                    fs.Write(buffer, 0, readsize)
                                    OnDownloadProgressChanged(Me, New DownloadProgressArgs(_TotalBytesReceived, _ContentLenght))
                                Loop While isRead
                            End Using
                        End Using
                    End If
                End Using
                OnDownloadCompleted(Me, New DownloadCompletedArgs(True))
            Catch ex As WebException
                OnDownloadCompleted(Me, New DownloadCompletedArgs(False))
            End Try
        End Sub
     
    End Class
     
    Class DownloadProgressArgs
     
        Private _BytesReceived As Integer
        Private _TotalBytesReceived As Integer
     
        Public Sub New(ByVal BytesReceived As Integer, ByVal TotalBytesReceived As Integer)
            _BytesReceived = BytesReceived
            _TotalBytesReceived = TotalBytesReceived
        End Sub
     
        Public ReadOnly Property BytesReceived As Integer
            Get
                Return _BytesReceived
            End Get
        End Property
     
        Public ReadOnly Property TotalBytesReceived As Integer
            Get
                Return _TotalBytesReceived
            End Get
        End Property
     
        Public ReadOnly Property ProgressPercentage As Integer
            Get
                If _TotalBytesReceived > 0 Then
                    Return Math.Ceiling((_BytesReceived / _TotalBytesReceived) * 100)
                Else
                    Return 0
                End If
            End Get
        End Property
    End Class
     
    Class DownloadCompletedArgs
     
        Private _ErrorMessage As Boolean
     
        Sub New(ErrorMessage As Boolean)
            _ErrorMessage = ErrorMessage
        End Sub
     
        Public ReadOnly Property ErrorMessage As Boolean
            Get
                Return _ErrorMessage
            End Get
        End Property
    End Class
    pouvez-vous m'aider à télécharger 2 fichier a la fois. Merci d'avance

  2. #2
    Membre actif
    Homme Profil pro
    Étudiant
    Inscrit en
    Janvier 2018
    Messages
    321
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Janvier 2018
    Messages : 321
    Points : 261
    Points
    261
    Par défaut
    Bonsoir, j'ai refait mon code mais j'arrive pas à comprendre pourquoi j'arrive pas a afficher le téléchargement dans listview.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    Imports System.IO
    Imports System.Threading
     
    Public Class Downloader
     
        Private _instances As New ArrayList()
        Private _threads As New ArrayList()
        Private _activeDownloadCount As Integer = 0
        Private _lockObject As New Object()
        Private Delegate Sub delSetStatus(ByVal Status As String, ByVal Mycolor As Color, ByVal f As FileDownloader)
        Public Shared Sub InfoDownloader(Names As String, URL As String, destination As String)
            Downloader._instances = New ArrayList()
            Downloader._threads = New ArrayList()
            Downloader._activeDownloadCount = 0
            Dim download As FileDownloader = Nothing
            Downloader.LvDownload.Items.Add(New ListViewItem(New String() {Names, ""}))
            For Each item As ListViewItem In Downloader.LvDownload.Items
                item.SubItems(1).Text = "Patienter le téléchargement...."
                item.SubItems(1).ForeColor = Color.Blue
                item.UseItemStyleForSubItems = False
                download = New FileDownloader(URL, Path.Combine(destination, Names & Path.GetExtension(URL)))
                item.Tag = download
                Try
                    Dim tsDelegate As New ThreadStart(AddressOf download.StartDownload)
                    AddHandler download.DownloadStarting, New FileDownloader._DownloadStarting(AddressOf download_DownloadStarting)
                    AddHandler download.DownloadCompleted, New FileDownloader.DownloadCompletedEventHandler(AddressOf download_DownloadCompleted)
                    AddHandler download.DownloadProgressChanged, New FileDownloader.ProgressChangedEventHandler(AddressOf download_DownloadProgress)
                    Dim t As New Thread(tsDelegate)
                    t.Name = item.SubItems(0).Text
                    Downloader._threads.Add(t)
                    Downloader._instances.Add(download)
                Catch ex As ObjectDisposedException
                    item.SubItems(1).Text = "Erreur de téléchargement !"
                    item.SubItems(1).ForeColor = Color.Red
                End Try
            Next
            StartDownload()
        End Sub
     
        Private Shared Sub download_DownloadCompleted(thread As FileDownloader, e As DownloadCompletedArgs)
            If e.Error IsNot Nothing Then
                SetStatus("Erreur de Téléchargement...", Color.Red, thread)
                Return
            Else
                SyncLock Downloader._lockObject
                    Downloader._activeDownloadCount -= 1
                End SyncLock
                SetStatus("Téléchargement terminé...", Color.Blue, thread)
                StartDownload()
                Return
            End If
        End Sub
     
        Private Shared Sub download_DownloadProgress(thread As FileDownloader, e As DownloadProgressArgs)
            SetStatus("Téléchargement( " & Downloader.GetFileSize(e.TotalBytesReceived) & " \ " & Downloader.GetFileSize(e.BytesReceived) & " ) - " & e.ProgressPercentage & " %", Color.Green, thread)
        End Sub
     
        Private Shared Sub download_DownloadStarting(ByVal thread As FileDownloader)
            SetStatus("Le téléchargement va bientôt commencer...", Color.Green, thread)
        End Sub
     
        Private Shared Sub StartDownload()
            Dim j As Integer = 0
            Dim limit As Integer = CInt(Form1.NumericUpDown1.Value)
            Dim iCount As Integer = 0
            SyncLock Downloader._lockObject
                iCount = Downloader._instances.Count
            End SyncLock
            If (iCount <> 0) Then
                For Each thread As Thread In Downloader._threads
                    Dim file As FileDownloader = CType(Downloader._instances(j), FileDownloader)
                    If file._IsStarted = False Then
                        SyncLock Downloader._lockObject
                            thread.Start()
                            Downloader._activeDownloadCount += 1
                        End SyncLock
                    End If
                    If Downloader._activeDownloadCount = limit Then
                        Exit For
                    End If
                    j += 1
                Next
            End If
        End Sub
     
        Private Shared Sub SetStatus(ByVal Status As String, ByVal colorLVi As Color, ByVal f As FileDownloader)
            If Downloader.LvDownload.InvokeRequired Then
                Dim method As New delSetStatus(AddressOf SetStatus)
                Downloader.Invoke(method, New Object() {Status, colorLVi, f})
            Else
                For Each item As ListViewItem In Downloader.LvDownload.Items
                    If item.Tag Is f Then
                        SyncLock Downloader._lockObject
                            item.SubItems(1).Text = Status
                            item.SubItems(1).ForeColor = colorLVi
                        End SyncLock
                        Exit For
                    End If
                Next
            End If
        End Sub
     
        Private Function GetFileSize(Type As Long) As String
            Dim types As String() = {"Byte", "KB", "MB", "GB"}
            Dim typees As Double = Type
            Dim CSA As Integer = 0
            While typees >= 1024 AndAlso CSA + 1 < types.Length
                CSA += 1
                typees = typees / 1024
            End While
            Return [String].Format("{0:0.##} {1}", typees, types(CSA))
        End Function
     
        Private Sub Download_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
            If Me._threads.Count > 0 Then
                If (MessageBox.Show("Voulez-vous annuler les téléchargements actifs.", "Annulé", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK) Then
                    Me.KillThreads()
                Else
                    e.Cancel = True
                End If
            End If
        End Sub
     
        Private Sub KillThreads()
            For Each thread As Thread In Me._threads
                If thread.IsAlive Then
                    thread.Abort()
                    thread.Interrupt()
                End If
            Next
            Me._threads = New ArrayList
            Me._instances = New ArrayList
        End Sub
    End Class
    mon code FileDownloader :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    Imports System.Net
    Imports System.IO
     
    Public Class FileDownloader
     
        Private _Url As String = String.Empty
        Private _DirectoryPath As String = String.Empty
        Public _IsStarted As Boolean = False
        Public Delegate Sub _DownloadStarting(ByVal thread As FileDownloader)
        Public Event DownloadStarting As _DownloadStarting
        Public Delegate Sub ProgressChangedEventHandler(ByVal thread As FileDownloader, ByVal e As DownloadProgressArgs)
        Public Event DownloadProgressChanged As ProgressChangedEventHandler
        Public Delegate Sub DownloadCompletedEventHandler(ByVal thread As FileDownloader, ByVal e As DownloadCompletedArgs)
        Public Event DownloadCompleted As DownloadCompletedEventHandler
     
        Protected Overridable Sub OnDownloadStarting(ByVal thread As FileDownloader)
            RaiseEvent DownloadStarting(Me)
        End Sub
        Protected Overridable Sub OnDownloadProgress(ByVal thread As FileDownloader, ByVal e As DownloadProgressArgs)
            RaiseEvent DownloadProgressChanged(Me, e)
        End Sub
        Protected Overridable Sub OnDownloadCompleted(ByVal thread As FileDownloader, ByVal e As DownloadCompletedArgs)
            RaiseEvent DownloadCompleted(Me, e)
        End Sub
     
        Public Sub New(ByVal Url As String, ByVal directory As String)
            _Url = Url
            _DirectoryPath = directory
        End Sub
     
        Public Sub StartDownload()
            If String.IsNullOrEmpty(_Url) Then
                Throw New ArgumentException("Veuillez fournir un URL.")
            End If
            If String.IsNullOrEmpty(_DirectoryPath) Then
                Throw New ArgumentException("Veuillez fournir une destination.")
            End If
            _IsStarted = True
            onDownloadStarting(Me)
            Try
                Dim request As HttpWebRequest = CType(WebRequest.Create(New Uri(_Url)), HttpWebRequest)
                With request
                    .Method = "GET"
                    .Timeout = 20000
                    .KeepAlive = True
                    .UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"
                End With
                Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                    If response.StatusCode = HttpStatusCode.OK Then
                        Dim _ContentLenght As Integer = response.ContentLength
                        Using stream As Stream = response.GetResponseStream()
                            Using fs As New FileStream(_DirectoryPath, FileMode.Create, FileAccess.Write, FileShare.Write)
                                Dim buffer As Byte() = New Byte(4096 - 1) {}
                                Dim _TotalBytesReceived As Integer = 0
                                Dim isRead As Boolean = True
                                Do
                                    Dim readsize As Integer = stream.Read(buffer, 0, buffer.Length)
                                    If readsize = 0 Then
                                        isRead = False
                                        Exit Do
                                    End If
                                    _TotalBytesReceived += readsize
                                    fs.Write(buffer, 0, readsize)
                                    OnDownloadProgress(Me, New DownloadProgressArgs(_TotalBytesReceived, _ContentLenght))
                                Loop While isRead
                            End Using
                        End Using
                    End If
                End Using
                OnDownloadCompleted(Me, New DownloadCompletedArgs(Nothing, False))
            Catch ex As Exception
                OnDownloadCompleted(Me, New DownloadCompletedArgs(ex, False))
            End Try
        End Sub
    End Class
     
    Public Class DownloadCompletedArgs : Inherits System.EventArgs
     
        Private _Error As Exception
        Private _Cancelled As Boolean
     
        Public Sub New(ByVal Err As Exception, ByVal Cancelled As Boolean)
            _Error = Err
            _Cancelled = Cancelled
        End Sub
     
        Public ReadOnly Property [Error]() As Exception
            Get
                Return _Error
            End Get
        End Property
     
        Public ReadOnly Property Cancelled() As Boolean
            Get
                Return _Cancelled
            End Get
        End Property
    End Class
     
    Public Class DownloadProgressArgs : Inherits System.EventArgs
     
        Private _BytesReceived As Integer
        Private _TotalBytesReceived As Integer
     
        Public Sub New(ByVal BytesReceived As Integer, ByVal TotalBytesReceived As Integer)
            _BytesReceived = BytesReceived
            _TotalBytesReceived = TotalBytesReceived
        End Sub
     
        Public ReadOnly Property BytesReceived As Integer
            Get
                Return _BytesReceived
            End Get
        End Property
     
        Public ReadOnly Property TotalBytesReceived As Integer
            Get
                Return _TotalBytesReceived
            End Get
        End Property
     
        Public ReadOnly Property ProgressPercentage As Integer
            Get
                If _TotalBytesReceived > 0 Then
                    Return Math.Ceiling((_BytesReceived / _TotalBytesReceived) * 100)
                Else
                    Return 0
                End If
            End Get
        End Property

    j'arrive pas à comprendre pourquoi ça affiche pas dans listview le téléchargement dans la form download? aider moi svp....

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Download multiple file
    Par Miska59 dans le forum VB.NET
    Réponses: 0
    Dernier message: 25/02/2021, 22h12
  2. [PHP 5.3] download multiple pdf files
    Par flora806 dans le forum Langage
    Réponses: 7
    Dernier message: 23/01/2015, 11h56
  3. [Upload] Upload multiple files
    Par aymanov dans le forum Langage
    Réponses: 17
    Dernier message: 22/12/2008, 10h38
  4. download multiple et en même temps
    Par manuplt dans le forum Langage
    Réponses: 3
    Dernier message: 12/07/2006, 16h38
  5. Download INI File
    Par K.othmane dans le forum Langage
    Réponses: 2
    Dernier message: 09/02/2006, 21h40

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo