Commentçamarche.net
CodeS-SourceS
Rechercher un code, un tuto, une réponse

[.net2] classe de téléchargement http avec gestion de resume, progression, authentification, proxy, évenement threads-safe..

5/5 (10 avis)

Vue 11 469 fois - Téléchargée 817 fois


Description

Hello le monde.
Voila une évolution de la classe que j'avais ecrit pour vb2002/2003 (présente sur le site).
Celle ci gère (heuresement) tout ce que fesait l'ancienne : resume, progression, proxy
Et les nouveautés :
_C'est maintenant une "vraie" classe
_Gestion de l'authentification type htaccess
_Gestion événement permettant des accés "thread-safe" aux controles des forms (le problème ne se posait pas en 2003, du moins aucunes exception n'était levée)
_Gestion d'erreures (simplistes, mais présente)
_Gestion des fichiers dont la taille n'est pas renvoyé par le header

Pourquoi n'ai je pas simplement fait une mise à jour du code exisant?
_Le sample accompagnant la classe a du être modifié, l'ancien n'est pas compatible avec cette nouvelle classe
_Les backgroundworker utilisé pour les renvoit d'évenement n'existent pas avant .Net 2.0
_La classe a été completement réecrite proprement
_L'ancienne classe marche très bien sous vb2002/2003

Cependant, si un admin juge qu'une simple mise à jour aurait suffit, la suppression de cette source ne me vexera pas ^^

Source / Exemple :


Option Strict On
Imports System.Net

Public Class HBDownloader2005

#Region "évenements"
    Public Event download_Started(ByVal sender As Object, ByVal totalfilelen As Long, ByVal resumepos As Long, ByVal TimeTickStart As Long)
    Public Event download_Progress(ByVal sender As Object, ByVal CurPosition As Long, ByVal CurPercentage As Integer)
    Public Event download_Ended(ByVal sender As Object, ByVal EndPosition As Long, ByVal CurPercentage As Integer)
    Public Event download_Error(ByVal sender As Object, ByVal ex As Exception)
#End Region

#Region "attributs"
    Private b As Boolean
    Private WithEvents bgw As System.ComponentModel.BackgroundWorker
    Private BufSize As Integer = 32768
    Private BytesArr(BufSize) As Byte
    Private CurPos As Long
    Private FileLength As Long
    Private Hwebrequest As HttpWebRequest
    Private IsResume As Boolean
    Private ReadStream As IO.Stream
    Private ResumePos As Long
    Private StartTime As DateTime
    Private TargetPath As String
    Private FileUrl As String
#End Region

#Region "proprietés"
    Public Property BufferSize() As Integer
        Get
            Return BufSize
        End Get
        Set(ByVal value As Integer)
            BufSize = value
            Array.Resize(BytesArr, BufSize)
        End Set
    End Property
    Public ReadOnly Property Start_Time() As Date
        Get
            Return StartTime
        End Get
    End Property

    Public ReadOnly Property Start_Tick() As Long
        Get
            Return StartTime.Ticks
        End Get
    End Property
#End Region

#Region "méthodes"
    Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean)
        Start(pathstr, strurl, IsResume, "", "", Nothing, Nothing)
    End Sub

    Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal login As String, ByVal pass As String)
        Start(pathstr, strurl, IsResume, login, pass, Nothing, Nothing)
    End Sub

    Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal proxy As String, ByVal proxyport As Integer)
        Start(pathstr, strurl, IsResume, "", "", proxy, proxyport)
    End Sub

    Public Sub Start(ByVal pathstr As String, ByVal strurl As String, ByVal bresume As Boolean, ByVal login As String, ByVal pass As String, ByVal proxy As String, ByVal proxyport As Integer)
        b = True
        IsResume = bresume
        StartTime = Now
        TargetPath = pathstr
        FileUrl = strurl
        Open_request(strurl, pathstr, login, pass, proxy, proxyport)
    End Sub

    Public Sub Stop_Download()
        b = False
    End Sub

    Private Sub Open_request(ByVal fileurl As String, ByVal filepath As String, ByVal login As String, ByVal pass As String, ByVal proxy As String, ByVal proxyport As Integer)
        Try
            If proxy <> "" Then
                Dim hproxy As WebProxy
                hproxy = New WebProxy(proxy, proxyport)
                WebRequest.DefaultWebProxy = hproxy
            End If
            Hwebrequest = CType(System.Net.HttpWebRequest.Create(fileurl), System.Net.HttpWebRequest)
            If login <> "" Then
                Dim hcredential As New System.Net.NetworkCredential(login, pass)
                Hwebrequest.Credentials = hcredential
            End If
            If IsResume = True Then
                ResumePos = FileLen(filepath)
                CurPos = ResumePos
                Hwebrequest.AddRange(CInt(CurPos))
            End If
            Dim hwebresponse As System.Net.HttpWebResponse = CType(Hwebrequest.GetResponse, System.Net.HttpWebResponse)
            ReadStream = hwebresponse.GetResponseStream
            FileLength = hwebresponse.ContentLength + CurPos
            StartTime = Now
            RaiseEvent download_Started(Me, FileLength, ResumePos, StartTime.Ticks)
            bgw = New System.ComponentModel.BackgroundWorker
            bgw.WorkerReportsProgress = True
            bgw.RunWorkerAsync()
        Catch ex As Exception
            RaiseEvent download_Error(Me, ex)
        End Try
    End Sub

    Private Function Get_Percentage(ByVal tmppos As Long, ByVal totallen As Long) As Integer
        Dim tmpres As Long
        If totallen > 0 Then
            tmpres = CLng((tmppos / totallen) * 100)
        Else 'si la taille du fichier n'était pas connue
            tmpres = -1
        End If
        Return CInt(tmpres)
    End Function

    Private Sub Get_file(ByVal filepath As String)
        Try
            Dim tmplen As Integer
            b = True
            Do
                tmplen = ReadStream.Read(BytesArr, 0, BufSize)
                CurPos += tmplen
                Dim filesave As New IO.FileStream(filepath, IO.FileMode.Append, IO.FileAccess.Write)
                filesave.Write(BytesArr, 0, tmplen)
                filesave.Close()
                bgw.ReportProgress(Get_Percentage(CurPos, FileLength))
                System.Threading.Thread.Sleep(1)
            Loop While (tmplen > 0 And b = True)
            b = False
            ReadStream.Close()
        Catch ex As Exception
            RaiseEvent download_Error(Me, ex)
        End Try
    End Sub

    Private Sub bgw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        Get_file(TargetPath)
    End Sub

    Private Sub bgw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
        RaiseEvent download_Progress(Me, CurPos, e.ProgressPercentage)
    End Sub

    Private Sub bgw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
        RaiseEvent download_Ended(Me, CurPos, Get_Percentage(CurPos, FileLength))
    End Sub
#End Region

End Class

Conclusion :


Commentaires? :)

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.