dotnet/winforms

Refactor VB's Application Framework Network Class

Open

#9 807 ouverte le 30 août 2023

Voir sur GitHub
 (28 commentaires) (0 réactions) (1 assigné)C# (922 forks)batch import
:construction: work in progressarea-VisualBasichelp wantedpriority-2

Métriques du dépôt

Stars
 (4 100 stars)
Métriques de merge PR
 (Merge moyen 14j 22h) (56 PRs mergées en 30 j)

Description

The class Microsoft.VisualBasic.Devices.Network, which is part of the Visual Basic Application Framework, is based on the obsoleted WebClient class.

We need to modernize this part of the Application Framework to avoid breaking changes, should the WebClient class no longer be included in future versions of .NET.

This should be done in the .NET 9-time frame.

This also addresses https://github.com/dotnet/winforms/issues/3936.

Here is a potential general approach, which uses HttpClient instead of WebClient. (!not tested, and my last Web-dev-experiences is quite a while, so, please double-check me here!)

Imports System.IO
Imports System.Net
Imports System.Net.Http

Public Class Network

    Public Async Function DownloadFileWithCredentialsAndProgressAsAStartingPointAsync(
        url As String,
        destinationPath As String,
        credentials As NetworkCredential,
        progress As IProgress(Of Double)) As Task

        Dim handler As New HttpClientHandler() With
        {
            .Credentials = credentials
        }

        Using httpClient As New HttpClient(handler)

            Dim response = Await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)
            Dim contentLength = response.Content.Headers.ContentLength

            Using responseStream As Stream = Await response.Content.ReadAsStreamAsync()
                Using fileStream As New FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None)

                    Dim buffer(8191) As Byte
                    Dim totalBytesRead As Long = 0
                    Dim bytesRead As Integer

                    While (Await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0
                        Await fileStream.WriteAsync(buffer, 0, bytesRead)
                        totalBytesRead += bytesRead

                        If contentLength.HasValue Then
                            Dim percentage As Double = (CDbl(totalBytesRead) / CDbl(contentLength.Value)) * 100
                            progress.Report(percentage)
                        End If

                    End While
                End Using
            End Using
        End Using
    End Function
End Class

Guide contributeur